import { useState, useCallback } from 'react';
import { UploadCloud, FileIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useTranslate } from '@/utils/i18n';

interface UploadAreaProps {
  onUpload: (file: File) => Promise<void>;
  isLoading?: boolean;
  acceptedTypes?: string[];
  maxSizeMB?: number;
}

export default function UploadArea({
  onUpload,
  isLoading = false,
  acceptedTypes = ['.docx', '.pdf', '.txt'],
  maxSizeMB = 50,
}: UploadAreaProps) {
  const t = useTranslate();
  const [isDragging, setIsDragging] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const validateFile = (file: File): string | null => {
    if (!acceptedTypes.some(type => file.type.includes(type.replace('.', '')))) {
      return `Invalid file type. Accepted: ${acceptedTypes.join(', ')}`;
    }
    if (file.size > maxSizeMB * 1024 * 1024) {
      return `File too large. Max size: ${maxSizeMB}MB`;
    }
    return null;
  };

  const handleDrop = useCallback(async (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    setError(null);

    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
      const file = files[0];
      const validationError = validateFile(file);
      if (validationError) {
        setError(validationError);
        return;
      }
      try {
        await onUpload(file);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Upload failed');
      }
    }
  }, [onUpload, acceptedTypes, maxSizeMB]);

  const handleFileInput = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    setError(null);
    const files = e.target.files;
    if (files && files.length > 0) {
      const file = files[0];
      const validationError = validateFile(file);
      if (validationError) {
        setError(validationError);
        return;
      }
      try {
        await onUpload(file);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Upload failed');
      }
    }
    // Reset input
    e.target.value = '';
  }, [onUpload, acceptedTypes, maxSizeMB]);

  return (
    <div
      className={cn(
        'relative w-full p-8 border-2 border-dashed rounded-xl transition-all',
        isDragging
          ? 'border-primary bg-primary/5'
          : 'border-muted-foreground/25 hover:border-primary/50',
        error && 'border-red-500 bg-red-50'
      )}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      <input
        type="file"
        accept={acceptedTypes.join(',')}
        onChange={handleFileInput}
        disabled={isLoading}
        className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
      />

      <div className="flex flex-col items-center justify-center gap-3 text-center">
        {isLoading ? (
          <div className="animate-spin rounded-full h-10 w-10 border-2 border-primary border-t-transparent" />
        ) : (
          <UploadCloud className={cn(
            'w-10 h-auto text-muted-foreground',
            isDragging && 'text-primary'
          )} />
        )}

        <div>
          <p className="text-sm font-medium">
            {t('documents.drop_files_here') || 'Drop files here, or click to select'}
          </p>
          <p className="text-xs text-muted-foreground mt-1">
            {acceptedTypes.join(', ')} • Max {maxSizeMB}MB
          </p>
        </div>

        {error && (
          <p className="text-sm text-red-600 bg-red-50 px-3 py-1.5 rounded-md">
            {error}
          </p>
        )}
      </div>
    </div>
  );
}
