import { useState, useEffect } from 'react';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { ChevronLeftIcon } from 'lucide-react';

interface PageProps {
    flash: {
        analyzedData?: any;
        success?: string;
        error?: string;
    };
    [key: string]: any;
}

export default function ContractFormPage() {
    const { flash } = usePage<PageProps>().props;

    const [formData, setFormData] = useState({
        docType: '',
        docName: '',
        docNumber: '',
        internalParty: '',
        internalPartyAbbr: '',
        counterParty: '',
        duration: '',
        value: '',
        isSigned: false,
    });
    const [contractFile, setContractFile] = useState<File | null>(null);
    const [isAnalyzing, setIsAnalyzing] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [message, setMessage] = useState({ type: '', text: '' });

    useEffect(() => {
        if (flash?.analyzedData) {
            let data = flash.analyzedData;

            if (Array.isArray(data) && data.length > 0) {
                data = data[0].Text || data[0];
            } else if (data && data.Text) {
                data = data.Text;
            }

            setFormData((prev) => ({
                ...prev,
                docType: data.document_type || prev.docType,
                docName: data.document_name || prev.docName,
                docNumber: data.document_number || prev.docNumber,
                internalParty: data.internal_party || prev.internalParty,
                internalPartyAbbr:
                    data.internal_party_abbreviation || prev.internalPartyAbbr,
                counterParty: data.counterparty || prev.counterParty,
                duration:
                    data.expiration_date ||
                    data.effective_date ||
                    prev.duration,
                value: data.contract_value || prev.value,
                isSigned:
                    data.Contract_Sign &&
                    data.Contract_Sign !== 'null' &&
                    data.Contract_Sign !== null
                        ? true
                        : prev.isSigned,
            }));
        }
        if (flash?.success) {
            setMessage({ type: 'success', text: flash.success });
            setIsAnalyzing(false);
        }
        if (flash?.error) {
            setMessage({ type: 'error', text: flash.error });
            setIsAnalyzing(false);
        }
    }, [flash]);

    const handleChange = (
        e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
    ) => {
        const { name, value, type } = e.target as HTMLInputElement;
        setFormData((prev) => ({
            ...prev,
            [name]:
                type === 'checkbox'
                    ? (e.target as HTMLInputElement).checked
                    : value,
        }));
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            const allowedTypes = [
                'application/pdf',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'image/jpeg',
                'image/png',
                'image/jpg',
            ];

            if (!allowedTypes.includes(file.type)) {
                alert(
                    'Format file tidak didukung! Hanya menerima PDF, DOCX, atau Gambar (JPEG/PNG).',
                );
                return;
            }
            if (file.size > 10 * 1024 * 1024) {
                alert('Ukuran file tidak boleh lebih dari 10MB');
                return;
            }
            setContractFile(file);
        }
    };

    const handleAnalyzeDocument = () => {
        if (!contractFile) return;
        setIsAnalyzing(true);
        setMessage({
            type: 'info',
            text: 'Sedang menganalisis dokumen dengan AI...',
        });

        const formData = new FormData();
        formData.append('file', contractFile);

        router.post('/contracts/analyze', formData, {
            preserveState: true,
            preserveScroll: true,
            onError: (errors) => {
                setIsAnalyzing(false);
                if (errors.file) {
                    setMessage({ type: 'error', text: errors.file });
                } else {
                    setMessage({
                        type: 'error',
                        text: 'Gagal menganalisis dokumen.',
                    });
                }
            },
        });
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        const dataToSend = new FormData();
        dataToSend.append('docType', formData.docType);
        dataToSend.append('docName', formData.docName);
        dataToSend.append('docNumber', formData.docNumber);
        dataToSend.append('internalParty', formData.internalParty);
        dataToSend.append('internalPartyAbbr', formData.internalPartyAbbr);
        dataToSend.append('counterParty', formData.counterParty);
        dataToSend.append('duration', formData.duration);
        dataToSend.append('value', formData.value);
        dataToSend.append('isSigned', String(formData.isSigned));

        if (contractFile) {
            dataToSend.append('contract_file', contractFile);
        }

        router.post('/contracts', dataToSend, {
            onStart: () => {
                setIsSaving(true);
                setMessage({ type: '', text: '' });
            },
            onSuccess: () => {
                setMessage({
                    type: 'success',
                    text: 'Kontrak berhasil disimpan!',
                });
                setFormData({
                    docType: '',
                    docName: '',
                    docNumber: '',
                    internalParty: '',
                    internalPartyAbbr: '',
                    counterParty: '',
                    duration: '',
                    value: '',
                    isSigned: false,
                });
                setContractFile(null);
            },
            onError: (errors) => {
                console.error(errors);
                setMessage({
                    type: 'error',
                    text: 'Gagal menyimpan. Periksa kembali form anda.',
                });
            },
            onFinish: () => {
                setIsSaving(false);
            },
        });
    };

    return (
        <>
            <Head title="Upload Kontrak Baru" />

            <div className="min-h-screen bg-[#030712] px-4 py-12 text-slate-100 sm:px-6 lg:px-8">
                <div className="mx-auto max-w-4xl">
                    {/* Tombol Back */}
                    <div className="mb-6">
                        <Link
                            href="/dashboard"
                            className="flex items-center gap-2 text-sm font-medium text-slate-400 hover:text-white"
                        >
                            <ChevronLeftIcon className="h-4 w-4" /> Kembali ke
                            Dashboard
                        </Link>
                    </div>

                    {/* Form Item */}
                    <form
                        onSubmit={handleSubmit}
                        className="space-y-6 rounded-lg border border-slate-800 bg-slate-900 p-6 text-slate-100 shadow-md"
                    >
                        <h2 className="text-2xl font-bold text-white">
                            Upload Kontrak Baru
                        </h2>

                        {message.text && (
                            <div
                                className={`rounded-lg border p-4 text-sm ${message.type === 'success' ? 'border-green-800 bg-green-950/40 text-green-400' : message.type === 'info' ? 'border-blue-800 bg-blue-950/40 text-blue-400' : 'border-red-800 bg-red-950/40 text-red-400'}`}
                            >
                                {message.text}
                            </div>
                        )}

                        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Type Dokumen *
                                </label>
                                <input
                                    type="text"
                                    name="docType"
                                    value={formData.docType}
                                    onChange={handleChange}
                                    required
                                    placeholder="Contoh: Purchase Agreement, NDA, dll"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Nama Dokumen *
                                </label>
                                <input
                                    type="text"
                                    name="docName"
                                    value={formData.docName}
                                    onChange={handleChange}
                                    required
                                    placeholder="Masukkan nama dokumen"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Nomor Dokumen *
                                </label>
                                <input
                                    type="text"
                                    name="docNumber"
                                    value={formData.docNumber}
                                    onChange={handleChange}
                                    required
                                    placeholder="Contoh: DOC-2024-001"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Internal Party
                                </label>
                                <input
                                    type="text"
                                    name="internalParty"
                                    value={formData.internalParty}
                                    onChange={handleChange}
                                    placeholder="Nama perusahaan internal"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Singkatan PT Internal
                                </label>
                                <input
                                    type="text"
                                    name="internalPartyAbbr"
                                    value={formData.internalPartyAbbr}
                                    onChange={handleChange}
                                    placeholder="Contoh: PT ABC"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Counter Party *
                                </label>
                                <input
                                    type="text"
                                    name="counterParty"
                                    value={formData.counterParty}
                                    onChange={handleChange}
                                    required
                                    placeholder="Nama pihak yang bersangkutan"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Jangka Waktu Kontrak
                                </label>
                                <input
                                    type="text"
                                    name="duration"
                                    value={formData.duration}
                                    onChange={handleChange}
                                    placeholder="Contoh: 1 Tahun, 12 Bulan"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-slate-300">
                                    Nilai Kontrak (Rp)
                                </label>
                                <input
                                    type="number"
                                    name="value"
                                    value={formData.value}
                                    onChange={handleChange}
                                    placeholder="Contoh: 50000000"
                                    className="mt-1 w-full rounded-lg border border-slate-700 bg-slate-800 px-4 py-2 text-white placeholder-slate-500 focus:border-blue-500 focus:outline-none"
                                />
                            </div>

                            <div className="flex items-center">
                                <label className="flex cursor-pointer items-center space-x-3">
                                    <input
                                        type="checkbox"
                                        name="isSigned"
                                        checked={formData.isSigned}
                                        onChange={handleChange}
                                        className="h-4 w-4 rounded border-slate-700 bg-slate-800 text-blue-600 focus:ring-blue-500"
                                    />
                                    <span className="text-sm font-medium text-slate-300">
                                        Sudah Ditandatangani
                                    </span>
                                </label>
                            </div>

                            <div className="md:col-span-2">
                                <label className="block text-sm font-medium text-slate-300">
                                    Upload Dokumen Kontrak
                                </label>
                                <div className="relative mt-2 flex items-center justify-center rounded-lg border-2 border-dashed border-slate-700 bg-slate-800/40 px-6 py-10 text-center">
                                    <div>
                                        <svg
                                            className="mx-auto h-12 w-12 text-slate-500"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                strokeLinecap="round"
                                                strokeLinejoin="round"
                                                strokeWidth={2}
                                                d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
                                            />
                                        </svg>
                                        <p className="mt-2 text-sm text-slate-400">
                                            {contractFile ? (
                                                <span className="font-medium text-blue-400">
                                                    {contractFile.name}
                                                </span>
                                            ) : (
                                                'Pilih file PDF, Word, atau Gambar'
                                            )}
                                        </p>
                                        <p className="mb-4 text-xs text-slate-500">
                                            Maksimal 10MB
                                        </p>

                                        <input
                                            id="file-upload"
                                            type="file"
                                            accept=".pdf,.docx,image/jpeg,image/png,image/jpg"
                                            onChange={handleFileChange}
                                            className="hidden"
                                        />

                                        <div className="flex flex-col items-center justify-center gap-3 sm:flex-row">
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    document
                                                        .getElementById(
                                                            'file-upload',
                                                        )
                                                        ?.click()
                                                }
                                                className="inline-block rounded-lg bg-slate-700 px-4 py-2 text-sm font-medium text-white hover:bg-slate-600"
                                            >
                                                Pilih File
                                            </button>

                                            {contractFile && (
                                                <button
                                                    type="button"
                                                    onClick={
                                                        handleAnalyzeDocument
                                                    }
                                                    disabled={isAnalyzing}
                                                    className="inline-flex items-center gap-2 rounded-lg border border-blue-700 bg-blue-900/40 px-4 py-2 text-sm font-medium text-blue-400 hover:bg-blue-900/60 disabled:opacity-50"
                                                >
                                                    {isAnalyzing ? (
                                                        <>
                                                            <svg
                                                                className="mr-2 -ml-1 h-4 w-4 animate-spin text-blue-400"
                                                                xmlns="http://www.w3.org/2000/svg"
                                                                fill="none"
                                                                viewBox="0 0 24 24"
                                                            >
                                                                <circle
                                                                    className="opacity-25"
                                                                    cx="12"
                                                                    cy="12"
                                                                    r="10"
                                                                    stroke="currentColor"
                                                                    strokeWidth="4"
                                                                ></circle>
                                                                <path
                                                                    className="opacity-75"
                                                                    fill="currentColor"
                                                                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                                                                ></path>
                                                            </svg>
                                                            Menganalisis...
                                                        </>
                                                    ) : (
                                                        <>
                                                            ✨ Auto-fill dengan
                                                            AI
                                                        </>
                                                    )}
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <button
                            type="submit"
                            disabled={isSaving}
                            className="w-full rounded-lg bg-blue-600 py-2.5 font-medium text-white shadow-lg shadow-blue-900/20 transition-colors hover:bg-blue-700 disabled:opacity-50"
                        >
                            {isSaving ? 'Menyimpan...' : 'Simpan Kontrak'}
                        </button>
                    </form>
                </div>
            </div>
        </>
    );
}
