import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Upload, X, File, Trash2 } from "lucide-react";
import axios from "axios";

interface LampiranModalProps {
    isOpen: boolean;
    onClose: () => void;
    idMcIpal: number;
    kodeKomponen: string;
    namaKomponen: string;
    editable: boolean;
}

interface FileItem {
    name: string;
    size: number;
    path: string;
}

const LampiranModal: React.FC<LampiranModalProps> = ({
    isOpen,
    onClose,
    idMcIpal,
    kodeKomponen,
    namaKomponen,
    editable,
}) => {
    const [files, setFiles] = useState<FileItem[]>([]);
    const [isUploading, setIsUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [dragActive, setDragActive] = useState(false);

    useEffect(() => {
        if (isOpen) {
            loadFiles();
        }
    }, [isOpen, idMcIpal, kodeKomponen]);

    const loadFiles = async () => {
        try {
            const response = await axios.post(
                "/pelaporan/al/lampiran-syarat-teknis/list-files",
                {
                    idmcipal: idMcIpal,
                    kode_komponen: kodeKomponen,
                }
            );
            setFiles(response.data);
        } catch (error) {
            console.error("Error loading files:", error);
        }
    };

    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 (!editable) return;

        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            handleFiles(e.dataTransfer.files);
        }
    };

    const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (!editable) return;

        if (e.target.files && e.target.files.length > 0) {
            handleFiles(e.target.files);
        }
    };

    const handleFiles = async (fileList: FileList) => {
        setIsUploading(true);
        setUploadProgress(0);

        const formData = new FormData();
        for (let i = 0; i < fileList.length; i++) {
            formData.append("file[]", fileList[i]);
        }

        try {
            await axios.post(
                `/pelaporan/al/lampiran-syarat-teknis/upload-file/${idMcIpal}/${kodeKomponen}`,
                formData,
                {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                    onUploadProgress: (progressEvent) => {
                        if (progressEvent.total) {
                            const progress = Math.round(
                                (progressEvent.loaded * 100) /
                                    progressEvent.total
                            );
                            setUploadProgress(progress);
                        }
                    },
                }
            );

            loadFiles();
        } catch (error) {
            console.error("Error uploading files:", error);
        } finally {
            setIsUploading(false);
        }
    };

    const deleteFile = async (filePath: string) => {
        if (!editable) return;

        try {
            await axios.post(
                "/pelaporan/al/lampiran-syarat-teknis/delete-file",
                {
                    filePath,
                    idmcipal: idMcIpal,
                    kode_komponen: kodeKomponen,
                }
            );

            loadFiles();
        } catch (error) {
            console.error("Error deleting file:", error);
        }
    };

    const formatFileSize = (bytes: number): string => {
        if (bytes === 0) return "0 Bytes";

        const k = 1024;
        const sizes = ["Bytes", "KB", "MB", "GB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
            <div className="bg-white rounded-lg shadow-lg w-full max-w-3xl">
                <div className="p-4 border-b flex justify-between items-center">
                    <h2 className="font-semibold text-gray-800 text-lg">
                        Lampiran {kodeKomponen}: {namaKomponen}
                    </h2>
                    <button
                        onClick={onClose}
                        className="text-gray-500 hover:text-gray-700"
                    >
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {editable && (
                    <div className="p-4">
                        <div
                            className={`border-2 ${
                                dragActive
                                    ? "border-green-400 bg-green-50"
                                    : "border-dashed border-gray-300"
                            } rounded-lg p-8 text-center`}
                            onDragEnter={handleDrag}
                            onDragOver={handleDrag}
                            onDragLeave={handleDrag}
                            onDrop={handleDrop}
                        >
                            <input
                                type="file"
                                id="fileUpload"
                                multiple
                                className="hidden"
                                onChange={handleFileInput}
                            />
                            <label
                                htmlFor="fileUpload"
                                className="flex flex-col items-center justify-center cursor-pointer"
                            >
                                <Upload className="w-12 h-12 text-gray-400 mb-2" />
                                <p className="text-gray-600">
                                    {dragActive
                                        ? "Lepaskan file di sini"
                                        : "Seret dan lepaskan file di sini, atau klik untuk memilih file"}
                                </p>
                                <p className="text-gray-400 text-sm mt-1">
                                    Format yang didukung: PDF, JPG, PNG (max
                                    20MB)
                                </p>
                            </label>
                        </div>

                        {isUploading && (
                            <div className="mt-4">
                                <p className="text-sm text-gray-600 mb-1">
                                    Mengunggah: {uploadProgress}%
                                </p>
                                <div className="w-full bg-gray-200 rounded-full h-2.5">
                                    <div
                                        className="bg-green-600 h-2.5 rounded-full"
                                        style={{ width: `${uploadProgress}%` }}
                                    ></div>
                                </div>
                            </div>
                        )}
                    </div>
                )}

                <div className="p-4">
                    <h3 className="font-medium text-gray-800 mb-3">
                        File yang diunggah:
                    </h3>

                    {files.length === 0 ? (
                        <p className="text-gray-500 text-center py-4">
                            Belum ada file yang diunggah
                        </p>
                    ) : (
                        <div className="space-y-2 max-h-72 overflow-y-auto">
                            {files.map((file, index) => (
                                <div
                                    key={index}
                                    className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border border-gray-200"
                                >
                                    <div className="flex items-center">
                                        <File className="h-5 w-5 text-blue-500 mr-2" />
                                        <div>
                                            <p className="text-sm font-medium text-gray-700">
                                                {file.name}
                                            </p>
                                            <p className="text-xs text-gray-500">
                                                {formatFileSize(file.size)}
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex space-x-2">
                                        <a
                                            href={`/storage/${file.path}`}
                                            target="_blank"
                                            className="text-blue-600 hover:underline text-sm"
                                        >
                                            Lihat
                                        </a>
                                        {editable && (
                                            <button
                                                onClick={() =>
                                                    deleteFile(file.path)
                                                }
                                                className="text-red-500 hover:text-red-700"
                                            >
                                                <Trash2 className="h-4 w-4" />
                                            </button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <div className="p-4 border-t flex justify-end">
                    <Button onClick={onClose}>Tutup</Button>
                </div>
            </div>
        </div>
    );
};

export default LampiranModal;
