'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 Link from 'next/link';
import { FileText, Search, Download, Tag, ExternalLink, 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 { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { WidgetContainer } from '../../widget-container';
import { useDocuments, useClassifications, formatDocumentSize } from '@/hooks/integrations';

interface DocumentsWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  maxItems?: number;
  className?: string;
}

/**
 * Documents Widget - Displays recent ecoDMS documents with search
 */
export function DocumentsWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: DocumentsWidgetProps) {
  const t = useTranslations('widgets.documents');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedClassification, setSelectedClassification] = useState<string | null>(null);

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

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

  const hasFilters = searchQuery || selectedClassification;

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<FileText className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
      colSpan={2}
    >
      {/* Search and Filter */}
      <div className="mb-3 space-y-2">
        <div className="relative">
          <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="h-8 pl-8 text-sm"
          />
          {hasFilters && (
            <Button
              variant="ghost"
              size="icon"
              className="absolute right-1 top-1/2 h-6 w-6 -translate-y-1/2"
              onClick={handleClearFilters}
            >
              <X className="h-3 w-3" />
            </Button>
          )}
        </div>

        {/* Classification Tags */}
        {classifications && classifications.length > 0 && (
          <div className="flex flex-wrap gap-1">
            {classifications.slice(0, 5).map((classification) => (
              <Badge
                key={classification.id}
                variant={selectedClassification === classification.name ? 'default' : 'outline'}
                className="cursor-pointer text-xs"
                onClick={() =>
                  setSelectedClassification(
                    selectedClassification === classification.name ? null : classification.name
                  )
                }
              >
                <Tag className="mr-1 h-3 w-3" />
                {classification.name}
              </Badge>
            ))}
          </div>
        )}
      </div>

      <ScrollArea className="h-[180px] pr-2">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 3 }).map((_, i) => (
              <div key={i} className="flex items-center gap-3">
                <Skeleton className="h-10 w-10 rounded" />
                <div className="flex-1 space-y-2">
                  <Skeleton className="h-4 w-3/4" />
                  <Skeleton className="h-3 w-1/2" />
                </div>
              </div>
            ))}
          </div>
        ) : documents && documents.length > 0 ? (
          <div className="space-y-2">
            {documents.map((doc, index) => (
              <motion.div
                key={doc.id}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.2, delay: index * 0.05 }}
                className="flex items-start gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50"
              >
                <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 className="min-w-0 flex-1">
                  <p className="truncate font-medium">{doc.title}</p>
                  <div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
                    <Badge variant="outline" className="text-xs">
                      {doc.classification}
                    </Badge>
                    <span>{formatDocumentSize(doc.fileSize)}</span>
                  </div>
                  <div className="mt-1 flex flex-wrap gap-1">
                    {doc.tags.slice(0, 3).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 > 3 && (
                      <span className="text-xs text-muted-foreground">
                        +{doc.tags.length - 3}
                      </span>
                    )}
                  </div>
                  <p className="mt-1 text-xs text-muted-foreground">
                    {doc.createdBy} -{' '}
                    {formatDistanceToNow(doc.createdAt, {
                      addSuffix: true,
                      locale: dateLocale,
                    })}
                  </p>
                </div>

                {doc.downloadUrl && (
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 shrink-0"
                        asChild
                      >
                        <a href={doc.downloadUrl} download>
                          <Download className="h-4 w-4" />
                        </a>
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>{t('download')}</TooltipContent>
                  </Tooltip>
                )}
              </motion.div>
            ))}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {searchQuery || selectedClassification ? t('noResults') : t('noDocuments')}
          </div>
        )}
      </ScrollArea>

      {/* Footer link */}
      <div className="mt-3 border-t pt-3">
        <Button variant="ghost" size="sm" className="w-full" asChild>
          <Link href={`/${locale}/integrations/ecodms`}>
            <ExternalLink className="mr-2 h-4 w-4" />
            {t('openEcoDms')}
          </Link>
        </Button>
      </div>
    </WidgetContainer>
  );
}
