'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import { FileText, Search, Download, Tag, FolderOpen, Archive, X } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { useDocuments, useClassifications, formatDocumentSize } from '@/hooks/integrations';

interface EcoDmsContentProps {
  locale: string;
}

/**
 * ecoDMS integration content - displays documents with search
 */
export function EcoDmsContent({ locale }: EcoDmsContentProps) {
  const t = useTranslations('widgets.documents');
  const tInt = useTranslations('integrations');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedClassification, setSelectedClassification] = useState<string | null>(null);

  const { data: documents, isLoading: documentsLoading } = useDocuments({
    search: searchQuery || undefined,
    classification: selectedClassification || undefined,
  });
  const { data: classifications, isLoading: classificationsLoading } = useClassifications();
  const dateLocale = locale === 'de' ? de : enUS;

  const hasFilters = searchQuery || selectedClassification;

  const handleClearFilters = () => {
    setSearchQuery('');
    setSelectedClassification(null);
  };

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Dokumente</CardTitle>
            <FileText className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {documentsLoading ? <Skeleton className="h-8 w-12" /> : documents?.length ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Klassifikationen</CardTitle>
            <FolderOpen className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {classificationsLoading ? <Skeleton className="h-8 w-12" /> : classifications?.length ?? 0}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Archiviert</CardTitle>
            <Archive className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {classificationsLoading ? (
                <Skeleton className="h-8 w-12" />
              ) : (
                classifications?.reduce((sum, c) => sum + c.documentCount, 0) ?? 0
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Heute hinzugefuegt</CardTitle>
            <FileText className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">
              {documentsLoading ? (
                <Skeleton className="h-8 w-12" />
              ) : (
                documents?.filter((d) => {
                  const today = new Date();
                  const created = new Date(d.createdAt);
                  return created.toDateString() === today.toDateString();
                }).length ?? 0
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Classifications */}
      <Card>
        <CardHeader>
          <CardTitle>Klassifikationen</CardTitle>
          <CardDescription>Dokumentkategorien im Archiv</CardDescription>
        </CardHeader>
        <CardContent>
          {classificationsLoading ? (
            <div className="flex flex-wrap gap-2">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-8 w-24" />
              ))}
            </div>
          ) : classifications && classifications.length > 0 ? (
            <div className="flex flex-wrap gap-2">
              {classifications.map((classification) => (
                <Badge
                  key={classification.id}
                  variant={selectedClassification === classification.name ? 'default' : 'outline'}
                  className="cursor-pointer text-sm"
                  onClick={() =>
                    setSelectedClassification(
                      selectedClassification === classification.name ? null : classification.name
                    )
                  }
                >
                  <Tag className="mr-1 h-3 w-3" />
                  {classification.name}
                  <span className="ml-1 rounded-full bg-muted px-1.5 text-xs">
                    {classification.documentCount}
                  </span>
                </Badge>
              ))}
            </div>
          ) : (
            <p className="text-muted-foreground">{tInt('noClassificationsFound')}</p>
          )}
        </CardContent>
      </Card>

      {/* Documents */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Dokumente</CardTitle>
              <CardDescription>Dokumente aus dem ecoDMS Archiv</CardDescription>
            </div>
            <div className="flex items-center gap-2">
              <div className="relative w-64">
                <Search className="absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={t('searchPlaceholder')}
                  className="pl-8"
                />
              </div>
              {hasFilters && (
                <Button variant="ghost" size="icon" onClick={handleClearFilters}>
                  <X className="h-4 w-4" />
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <ScrollArea className="h-[400px]">
            {documentsLoading ? (
              <div className="space-y-2">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : documents && documents.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Titel</TableHead>
                    <TableHead>Klassifikation</TableHead>
                    <TableHead>Tags</TableHead>
                    <TableHead>Groesse</TableHead>
                    <TableHead>Erstellt</TableHead>
                    <TableHead className="w-10"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {documents.map((doc, index) => (
                    <motion.tr
                      key={doc.id}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ duration: 0.2, delay: index * 0.03 }}
                      className="border-b transition-colors hover:bg-muted/50"
                    >
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-red-500/10 text-red-500">
                            <FileText className="h-5 w-5" />
                          </div>
                          <div>
                            <p className="font-medium">{doc.title}</p>
                            <p className="text-xs text-muted-foreground">{doc.fileName}</p>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{doc.classification}</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {doc.tags.slice(0, 2).map((tag) => (
                            <span
                              key={tag}
                              className="inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-xs"
                            >
                              {tag}
                            </span>
                          ))}
                          {doc.tags.length > 2 && (
                            <span className="text-xs text-muted-foreground">
                              +{doc.tags.length - 2}
                            </span>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-muted-foreground">
                        {formatDocumentSize(doc.fileSize)}
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          <p>{doc.createdBy}</p>
                          <p className="text-xs text-muted-foreground">
                            {formatDistanceToNow(doc.createdAt, {
                              addSuffix: true,
                              locale: dateLocale,
                            })}
                          </p>
                        </div>
                      </TableCell>
                      <TableCell>
                        {doc.downloadUrl && (
                          <Button variant="ghost" size="icon" asChild>
                            <a href={doc.downloadUrl} download>
                              <Download className="h-4 w-4" />
                            </a>
                          </Button>
                        )}
                      </TableCell>
                    </motion.tr>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="flex items-center justify-center py-8 text-muted-foreground">
                <FileText className="mr-2 h-5 w-5" />
                {hasFilters ? t('noResults') : t('noDocuments')}
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  );
}
