import { FileText, Clock, CheckCircle, AlertCircle, Loader2, MoreVertical, Download, Trash2, Edit, FileUp } from 'lucide-react';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/vi';
import { useState } from 'react';
import { cn } from '@/lib/utils';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ApiDocument } from '@/service/types';
import { useTranslate } from '@/utils/i18n';

dayjs.extend(relativeTime);

interface DocumentCardProps {
  document: ApiDocument;
  onProcess?: (docId: number) => void;
  onImport?: (docId: number) => void;
  onDelete?: (docId: number) => void;
  onUpdate?: (docId: number, updates: { title?: string; tags?: string[] }) => void;
  onClick?: (docId: number) => void;
}

const statusConfig = {
  PENDING: {
    icon: Clock,
    color: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    label: 'documents.status.pending',
  },
  PROCESSING: {
    icon: Loader2,
    color: 'bg-blue-100 text-blue-800 border-blue-200 animate-spin',
    label: 'documents.status.processing',
  },
  COMPLETED: {
    icon: CheckCircle,
    color: 'bg-green-100 text-green-800 border-green-200',
    label: 'documents.status.completed',
  },
  FAILED: {
    icon: AlertCircle,
    color: 'bg-red-100 text-red-800 border-red-200',
    label: 'documents.status.failed',
  },
};

export default function DocumentCard({
  document,
  onProcess,
  onImport,
  onDelete,
  onUpdate,
  onClick,
}: DocumentCardProps) {
  const t = useTranslate();
  const [showActions, setShowActions] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState(document.title || document.original_filename);

  const status = statusConfig[document.status as keyof typeof statusConfig] || statusConfig.PENDING;
  const StatusIcon = status.icon;

  const getStatusLabel = (key: string) => {
    return t(`documents.status.${key}`) || key;
  };

  const handleSaveTitle = async () => {
    if (onUpdate && editTitle !== document.title) {
      await onUpdate(document.id, { title: editTitle });
    }
    setIsEditing(false);
  };

  const getFileIcon = () => {
    if (document.mime_type.includes('pdf')) return '📄';
    if (document.mime_type.includes('word') || document.mime_type.includes('document')) return '📘';
    return <FileText className="w-8 h-auto text-muted-foreground" />;
  };

  return (
    <div
      className={cn(
        'group relative bg-card border rounded-xl p-4 cursor-pointer transition-all',
        'hover:shadow-md hover:border-primary/30',
        onClick && 'hover:border-primary/50'
      )}
      onClick={() => onClick?.(document.id)}
    >
      {/* Header with file icon and status */}
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="flex items-center gap-3 flex-1 min-w-0">
          <div className="flex-shrink-0">{getFileIcon()}</div>
          <div className="flex-1 min-w-0">
            {isEditing ? (
              <input
                type="text"
                value={editTitle}
                onChange={(e) => setEditTitle(e.target.value)}
                onBlur={handleSaveTitle}
                onKeyDown={(e) => e.key === 'Enter' && handleSaveTitle()}
                className="w-full text-sm font-medium bg-background border rounded px-1 py-0.5"
                autoFocus
                onClick={(e) => e.stopPropagation()}
              />
            ) : (
              <h3 className="text-sm font-medium truncate" title={document.title || document.original_filename}>
                {document.title || document.original_filename}
              </h3>
            )}
            <p className="text-xs text-muted-foreground mt-0.5">
              {(document.file_size / 1024).toFixed(1)} KB
              {document.pages && ` • ${document.pages} pages`}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-2 flex-shrink-0">
          <Badge variant="outline" className={cn('text-xs flex items-center gap-1', status.color)}>
            <StatusIcon className="w-3 h-3" />
            {getStatusLabel(document.status)}
          </Badge>

          <DropdownMenu open={showActions} onOpenChange={setShowActions}>
            <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
              <Button variant="ghost" size="icon" className="w-8 h-8">
                <MoreVertical className="w-4 h-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {document.status === 'COMPLETED' && (
                <>
                  <DropdownMenuItem onClick={(e) => { e.stopPropagation(); onProcess?.(document.id); }}>
                    <FileUp className="w-4 h-4 mr-2" />
                    {t('documents.ai_enhance.enhance')}
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={(e) => { e.stopPropagation(); onImport?.(document.id); }}>
                    <Download className="w-4 h-4 mr-2" />
                    {t('documents.import_to_memo')}
                  </DropdownMenuItem>
                </>
              )}
              {document.status === 'PENDING' && (
                <DropdownMenuItem onClick={(e) => { e.stopPropagation(); onProcess?.(document.id); }}>
                  <Clock className="w-4 h-4 mr-2" />
                  {t('documents.ai_enhance.processing')}
                </DropdownMenuItem>
              )}
              <DropdownMenuItem onClick={(e) => { e.stopPropagation(); onUpdate?.(document.id, {}); setIsEditing(true); }}>
                <Edit className="w-4 h-4 mr-2" />
                {t('common.edit')}
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={(e) => { e.stopPropagation(); onDelete?.(document.id); }}
                className="text-red-600"
              >
                <Trash2 className="w-4 h-4 mr-2" />
                {t('common.delete')}
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Summary preview */}
      {document.summary && (
        <p className="text-sm text-muted-foreground line-clamp-2 mb-3">
          {document.summary}
        </p>
      )}

      {/* Tags */}
      {document.tags && document.tags.length > 0 && (
        <div className="flex flex-wrap gap-1.5 mb-3">
          {document.tags.slice(0, 5).map((tag) => (
            <Badge key={tag} variant="secondary" className="text-xs">
              #{tag}
            </Badge>
          ))}
          {document.tags.length > 5 && (
            <Badge variant="secondary" className="text-xs">
              +{document.tags.length - 5} more
            </Badge>
          )}
        </div>
      )}

      {/* Footer */}
      <div className="flex items-center justify-between text-xs text-muted-foreground border-t pt-2">
        <span>
          {dayjs(document.created_at).locale('vi').fromNow()}
        </span>
        {document.ai_enhanced && (
          <Badge variant="outline" className="text-xs">
            ✨ AI Enhanced
          </Badge>
        )}
      </div>
    </div>
  );
}
