import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { X, Upload, FileText } from "lucide-react";
import { useState } from "react";

interface FileUploadProps {
  value?: {
    nomFichier: string;
    urlFichier: string;
    s3Key: string;
    typeFichier: string;
    tailleFichier: number;
  } | null;
  onChange: (file: {
    nomFichier: string;
    urlFichier: string;
    s3Key: string;
    typeFichier: string;
    tailleFichier: number;
  } | null) => void;
  accept?: string;
  maxSize?: number; // en Mo
}

export function FileUpload({ value, onChange, accept, maxSize = 10 }: FileUploadProps) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Vérifier la taille
    const fileSizeMB = file.size / (1024 * 1024);
    if (fileSizeMB > maxSize) {
      setError(`Le fichier est trop volumineux (max ${maxSize} Mo)`);
      return;
    }

    setError(null);
    setUploading(true);

    try {
      const formData = new FormData();
      formData.append("file", file);

      const response = await fetch("/api/upload-file", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("Erreur lors de l'upload");
      }

      const data = await response.json();
      
      onChange({
        nomFichier: file.name,
        urlFichier: data.url,
        s3Key: data.key,
        typeFichier: file.type,
        tailleFichier: file.size,
      });
    } catch (err) {
      console.error("Erreur upload:", err);
      setError("Erreur lors de l'upload du fichier");
    } finally {
      setUploading(false);
    }
  };

  const handleRemove = () => {
    onChange(null);
    setError(null);
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + " octets";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " Ko";
    return (bytes / (1024 * 1024)).toFixed(1) + " Mo";
  };

  return (
    <div className="space-y-2">
      <Label>Pièce jointe (optionnel)</Label>
      
      {!value ? (
        <div className="space-y-2">
          <div className="flex items-center gap-2">
            <Input
              type="file"
              onChange={handleFileChange}
              accept={accept}
              disabled={uploading}
              className="flex-1"
            />
            {uploading && (
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <div className="animate-spin h-4 w-4 border-2 border-primary border-t-transparent rounded-full" />
                Upload en cours...
              </div>
            )}
          </div>
          {error && (
            <p className="text-sm text-destructive">{error}</p>
          )}
          <p className="text-xs text-muted-foreground">
            Taille maximale : {maxSize} Mo
            {accept && ` • Formats acceptés : ${accept}`}
          </p>
        </div>
      ) : (
        <div className="flex items-center gap-2 p-3 border rounded-lg bg-muted/50">
          <FileText className="h-5 w-5 text-muted-foreground flex-shrink-0" />
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium truncate">{value.nomFichier}</p>
            <p className="text-xs text-muted-foreground">
              {formatFileSize(value.tailleFichier)}
            </p>
          </div>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={handleRemove}
            className="flex-shrink-0"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
      )}
    </div>
  );
}
