import { useRef, useState } from 'react';
import { Upload, Images } from 'lucide-react';
import Button from './Button';
import JpgToPdfModal from './JpgToPdfModal';

interface FileUploadProps {
  onUpload: (file: File) => Promise<void>;
  existingFile?: string;
  accept?: string;
  label?: string;
  disabled?: boolean;
  /** Standard: aktiv, sobald `accept` PDF einschließt. Explizit auf false setzen, um den Button auszublenden. */
  enableJpgToPdf?: boolean;
  /** Default-Name (ohne .pdf) für die aus JPGs erzeugte PDF. */
  jpgToPdfFileNameHint?: string;
}

export default function FileUpload({
  onUpload,
  existingFile,
  accept = '.pdf,.jpg,.jpeg,.png',
  label = 'Dokument hochladen',
  disabled = false,
  enableJpgToPdf,
  jpgToPdfFileNameHint,
}: FileUploadProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [dragOver, setDragOver] = useState(false);
  const [isJpgModalOpen, setIsJpgModalOpen] = useState(false);

  const acceptsPdf = /pdf/i.test(accept);
  const showJpgButton = (enableJpgToPdf ?? acceptsPdf) && !disabled;

  const handleFileSelect = async (file: File) => {
    if (!file) return;

    setIsUploading(true);
    try {
      await onUpload(file);
    } catch (error) {
      console.error('Upload failed:', error);
      alert('Upload fehlgeschlagen');
    } finally {
      setIsUploading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setDragOver(true);
  };

  const handleDragLeave = () => {
    setDragOver(false);
  };

  return (
    <div className="space-y-2">
      {existingFile ? (
        !disabled && (
          <div className="flex flex-wrap gap-2">
            <Button
              variant="secondary"
              size="sm"
              onClick={() => inputRef.current?.click()}
              disabled={isUploading}
            >
              {isUploading ? 'Wird hochgeladen...' : 'Ersetzen'}
            </Button>
            {showJpgButton && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsJpgModalOpen(true)}
                disabled={isUploading}
                title="Mehrere JPGs zu einer PDF kombinieren"
              >
                <Images className="w-4 h-4 mr-1" /> JPGs → PDF
              </Button>
            )}
          </div>
        )
      ) : (
        <>
          <div
            className={`border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${
              dragOver
                ? 'border-blue-500 bg-blue-50'
                : 'border-gray-300 hover:border-gray-400'
            } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
            onClick={() => !disabled && inputRef.current?.click()}
            onDrop={!disabled ? handleDrop : undefined}
            onDragOver={!disabled ? handleDragOver : undefined}
            onDragLeave={!disabled ? handleDragLeave : undefined}
          >
            {isUploading ? (
              <div className="text-gray-500">
                <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-2" />
                Wird hochgeladen...
              </div>
            ) : (
              <>
                <Upload className="w-6 h-6 text-gray-400 mx-auto mb-2" />
                <p className="text-sm text-gray-600">{label}</p>
                <p className="text-xs text-gray-400 mt-1">PDF, JPG oder PNG (max. 25 MB)</p>
              </>
            )}
          </div>
          {showJpgButton && !isUploading && (
            <div className="flex justify-center">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setIsJpgModalOpen(true)}
                title="Mehrere JPGs zu einer PDF kombinieren"
              >
                <Images className="w-4 h-4 mr-1" /> JPGs → PDF
              </Button>
            </div>
          )}
        </>
      )}

      <input
        ref={inputRef}
        type="file"
        accept={accept}
        onChange={handleChange}
        className="hidden"
        disabled={disabled || isUploading}
      />

      <JpgToPdfModal
        isOpen={isJpgModalOpen}
        onClose={() => setIsJpgModalOpen(false)}
        onComplete={(file) => {
          handleFileSelect(file);
        }}
        fileNameHint={jpgToPdfFileNameHint}
      />
    </div>
  );
}
