"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { Upload, X, File, Image as ImageIcon, Loader2 } from "lucide-react";
import { toast } from "sonner";

interface FileUploadProps {
  label: string;
  category: string;
  currentFile?: string;
  onFileUploaded: (filePath: string) => void;
  onFileRemoved: () => void;
  accept?: string;
  maxSize?: number; // dalam MB
  description?: string;
}

export function FileUpload({
  label,
  category,
  currentFile,
  onFileUploaded,
  onFileRemoved,
  accept = "image/*,.pdf,.doc,.docx",
  maxSize = 5,
  description,
}: FileUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileUpload = async (file: File) => {
    if (file.size > maxSize * 1024 * 1024) {
      toast.error(`File terlalu besar. Maksimal ${maxSize}MB`);
      return;
    }

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

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

      const result = await response.json();

      if (result.success) {
        onFileUploaded(result.data.path);
        toast.success("File berhasil diupload");
      } else {
        toast.error(result.message || "Gagal mengupload file");
      }
    } catch (error) {
      console.error("Upload error:", error);
      toast.error("Gagal mengupload file");
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileRemove = async () => {
    if (!currentFile) return;

    try {
      const response = await fetch(`/api/upload?path=${encodeURIComponent(currentFile)}`, {
        method: "DELETE",
      });

      const result = await response.json();

      if (result.success) {
        onFileRemoved();
        toast.success("File berhasil dihapus");
      } else {
        toast.error(result.message || "Gagal menghapus file");
      }
    } catch (error) {
      console.error("Delete error:", error);
      toast.error("Gagal menghapus file");
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileUpload(e.dataTransfer.files[0]);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileUpload(e.target.files[0]);
    }
  };

  const openFileDialog = () => {
    fileInputRef.current?.click();
  };

  const getFileIcon = (filePath: string) => {
    const extension = filePath.split('.').pop()?.toLowerCase();
    if (['jpg', 'jpeg', 'png', 'gif'].includes(extension || '')) {
      return <ImageIcon className="h-4 w-4" />;
    }
    return <File className="h-4 w-4" />;
  };

  const getFileName = (filePath: string) => {
    return filePath.split('/').pop() || filePath;
  };

  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      {description && (
        <p className="text-sm text-muted-foreground">{description}</p>
      )}

      {currentFile ? (
        <Card className="overflow-hidden">
          {['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(currentFile.split('.').pop()?.toLowerCase() || '') && (
             <div className="relative aspect-video w-full bg-muted flex items-center justify-center overflow-hidden bg-gray-100">
                 {/* Use img directly since we don't know if it's external or local, usually /uploads/ */}
                 <img src={currentFile} alt="Preview" className="h-full w-full object-contain" />
             </div>
          )}
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                {getFileIcon(currentFile)}
                <div className="overflow-hidden">
                  <p className="text-sm font-medium truncate max-w-[150px]">{getFileName(currentFile)}</p>
                  <p className="text-xs text-muted-foreground truncate max-w-[150px]">{currentFile}</p>
                </div>
              </div>
              <div className="flex items-center space-x-2">
                {currentFile.startsWith('/uploads/') && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => window.open(currentFile, '_blank')}
                  >
                    Lihat
                  </Button>
                )}
                <Button
                  type="button"
                  variant="destructive"
                  size="sm"
                  onClick={handleFileRemove}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Card
          className={`border-2 border-dashed transition-colors ${
            dragActive
              ? "border-primary bg-primary/10"
              : "border-muted-foreground/25 hover:border-muted-foreground/50"
          }`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <CardContent className="p-6">
            <div className="text-center">
              {isUploading ? (
                <div className="flex flex-col items-center space-y-2">
                  <Loader2 className="h-8 w-8 animate-spin text-primary" />
                  <p className="text-sm text-muted-foreground">Mengupload file...</p>
                </div>
              ) : (
                <div className="flex flex-col items-center space-y-2">
                  <Upload className="h-8 w-8 text-muted-foreground" />
                  <div className="space-y-1">
                    <p className="text-sm">
                      <Button
                        type="button"
                        variant="link"
                        className="p-0 h-auto text-primary"
                        onClick={openFileDialog}
                      >
                        Klik untuk upload
                      </Button>{" "}
                      atau drag & drop
                    </p>
                    <p className="text-xs text-muted-foreground">
                      Maksimal {maxSize}MB • JPG, PNG, PDF, DOC
                    </p>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      <Input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleInputChange}
        className="hidden"
      />
    </div>
  );
}
