import { useState } from 'react';
import { FolderOpen } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import DocumentCard from './DocumentCard';
import { useDocuments, useDocumentDelete, useDocumentProcess, useDocumentImport, useDocumentUpdate } from '@/hooks/useDocuments';
import { ApiDocument } from '@/service/types';
import { useTranslate } from '@/utils/i18n';
import Empty from '@/components/Empty';

interface DocumentListProps {
  workspaceId?: string;
  onSelectDocument?: (docId: number) => void;
}

export default function DocumentList({ workspaceId, onSelectDocument }: DocumentListProps) {
  const t = useTranslate();
  const [statusFilter, setStatusFilter] = useState<string>('');

  const { documents, total, isLoading, error, refetch } = useDocuments({
    workspace_id: workspaceId,
    status: statusFilter || undefined,
    limit: 50,
  });

  const deleteMutation = useDocumentDelete();
  const processMutation = useDocumentProcess();
  const importMutation = useDocumentImport();
  const updateMutation = useDocumentUpdate();

  const handleDelete = async (docId: number) => {
    if (confirm(t('documents.confirm_delete'))) {
      await deleteMutation.mutateAsync(docId);
    }
  };

  const handleProcess = async (docId: number) => {
    await processMutation.mutateAsync({
      docId,
      options: { enhance_with_ai: true, generate_summary: true, extract_tags: true },
    });
  };

  const handleImport = async (docId: number) => {
    await importMutation.mutateAsync({
      docId,
      importOptions: { create_as_memo: true, visibility: 'PRIVATE' },
    });
    alert(t('documents.import_success'));
  };

  const handleUpdate = async (docId: number, updates: { title?: string; tags?: string[] }) => {
    await updateMutation.mutateAsync({ docId, updates });
  };

  const getStatusOptions = () => [
    { value: '', label: t('documents.all_status') },
    { value: 'PENDING', label: t('documents.status.pending') },
    { value: 'PROCESSING', label: t('documents.status.processing') },
    { value: 'COMPLETED', label: t('documents.status.completed') },
    { value: 'FAILED', label: t('documents.status.failed') },
  ];

  if (isLoading && documents.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 gap-3">
        <div className="animate-spin rounded-full h-10 w-10 border-2 border-primary border-t-transparent" />
        <p className="text-sm text-muted-foreground">{t('common.loading')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <p className="text-red-600 mb-3">{t('common.error')}: {error.message}</p>
        <Button onClick={() => refetch()}>{t('common.retry')}</Button>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Filter bar */}
      {documents.length > 0 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            {t('documents.showing')} {documents.length} {t('documents.of')} {total} {t('documents.documents')}
          </p>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-40">
              <SelectValue placeholder={t('documents.filter_by_status')} />
            </SelectTrigger>
            <SelectContent>
              {getStatusOptions().map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* Document grid */}
      {documents.length === 0 ? (
        <Empty
          icon={FolderOpen}
          title={t('documents.empty.title')}
          description={t('documents.empty.description')}
        />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {documents.map((doc) => (
            <DocumentCard
              key={doc.id}
              document={doc}
              onProcess={handleProcess}
              onImport={handleImport}
              onDelete={handleDelete}
              onUpdate={handleUpdate}
              onClick={onSelectDocument}
            />
          ))}
        </div>
      )}
    </div>
  );
}
