import { useEffect, useRef, useState } from 'react';
import { Head, router } from '@inertiajs/react';
import { Button } from '@heroui/react';
import AppLayout from '@/Layouts/AppLayout';
import RichEditor from '@/Components/RichEditor/RichEditor';
import { api, getErrorMessage } from '@/lib/api';
import {
    ArrowLeftIcon,
    PhotoIcon,
    ArrowUpTrayIcon,
    XMarkIcon,
    SparklesIcon,
    CheckIcon,
} from '@heroicons/react/24/solid';

interface FormProps {
    id?: number;
}

interface PanduanData {
    title: string;
    category: 'teknis' | 'sop' | 'pengumuman' | 'lainnya';
    excerpt: string;
    content: string;
    cover_image: string;
    is_active: boolean;
    show_on_login: boolean;
    priority: number;
}

export default function PanduanForm({ id }: FormProps) {
    const isEdit = !!id;
    const fileInputRef = useRef<HTMLInputElement>(null);

    const [form, setForm] = useState<PanduanData>({
        title: '',
        category: 'teknis',
        excerpt: '',
        content: '',
        cover_image: '',
        is_active: true,
        show_on_login: false,
        priority: 0,
    });

    const [loading, setLoading] = useState(isEdit);
    const [saving, setSaving] = useState(false);
    const [uploadingCover, setUploadingCover] = useState(false);
    const [error, setError] = useState('');

    useEffect(() => {
        if (!id) return;
        let isMounted = true;
        setLoading(true);
        api.get(`/panduans/${id}`)
            .then((res) => {
                if (isMounted && res.data) {
                    setForm({
                        title: res.data.title || '',
                        category: res.data.category || 'teknis',
                        excerpt: res.data.excerpt || '',
                        content: res.data.content || '',
                        cover_image: res.data.cover_image || '',
                        is_active: res.data.is_active ?? true,
                        show_on_login: res.data.show_on_login ?? false,
                        priority: res.data.priority || 0,
                    });
                }
            })
            .catch((err) => {
                if (isMounted) {
                    setError(getErrorMessage(err, 'Gagal memuat data panduan.'));
                }
            })
            .finally(() => {
                if (isMounted) setLoading(false);
            });

        return () => {
            isMounted = false;
        };
    }, [id]);

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

        try {
            setUploadingCover(true);
            const formData = new FormData();
            formData.append('file', file);
            formData.append('folder', 'panduan-covers');

            const res = await api.post('/files', formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            if (res.data?.url) {
                setForm((prev) => ({ ...prev, cover_image: res.data.url }));
            }
        } catch (err) {
            alert(getErrorMessage(err, 'Gagal mengunggah gambar sampul.'));
        } finally {
            setUploadingCover(false);
        }
    };

    const handleSubmit = async (e?: React.FormEvent) => {
        if (e) e.preventDefault();
        if (!form.title.trim()) {
            alert('Judul panduan wajib diisi.');
            return;
        }
        if (!form.content.trim()) {
            alert('Konten panduan / tutorial wajib diisi.');
            return;
        }

        try {
            setSaving(true);
            if (isEdit) {
                await api.put(`/panduans/${id}`, form);
                router.visit(`/panduan/${id}`);
            } else {
                const res = await api.post('/panduans', form);
                const createdId = res.data?.id;
                router.visit(createdId ? `/panduan/${createdId}` : '/panduan');
            }
        } catch (err) {
            alert(getErrorMessage(err, 'Gagal menyimpan panduan.'));
            setSaving(false);
        }
    };

    if (loading) {
        return (
            <AppLayout>
                <div className="py-20 text-center text-sm text-gray-400">
                    Memuat formulir panduan...
                </div>
            </AppLayout>
        );
    }

    return (
        <AppLayout>
            <Head title={isEdit ? 'Edit Panduan & Teknis' : 'Buat Panduan & Teknis'} />

            <div className="flex flex-col gap-5">
                {/* Standard Top Bar Card */}
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-white border border-slate-200/80 px-4 sm:px-6 py-4 sm:py-4.5 rounded-2xl shadow-sm">
                    <div className="flex items-center gap-3 min-w-0">
                        <button
                            type="button"
                            onClick={() => router.visit(isEdit ? `/panduan/${id}` : '/panduan')}
                            className="p-1.5 rounded-lg border border-gray-200 hover:bg-gray-50 text-gray-600 transition shrink-0 cursor-pointer"
                            title="Kembali"
                        >
                            <ArrowLeftIcon className="w-4 h-4" />
                        </button>
                        <h1 className="text-lg sm:text-xl font-bold text-gray-900 truncate">
                            {isEdit ? 'Edit Panduan & Teknis' : 'Tambah Panduan Baru'}
                        </h1>
                    </div>

                    <div className="flex items-center gap-2 shrink-0">
                        <Button
                            variant="outline"
                            onPress={() => router.visit(isEdit ? `/panduan/${id}` : '/panduan')}
                            className="shrink-0"
                        >
                            Batal
                        </Button>
                        <Button
                            variant="primary"
                            onPress={() => handleSubmit()}
                            isDisabled={saving}
                            className="shrink-0"
                        >
                            <CheckIcon className="w-4 h-4" />
                            <span>{saving ? 'Menyimpan...' : 'Simpan'}</span>
                        </Button>
                    </div>
                </div>

                {error && (
                    <div className="p-4 rounded-xl bg-red-50 text-red-700 text-xs border border-red-200">
                        {error}
                    </div>
                )}

                {/* Form Content Card */}
                <form
                    onSubmit={handleSubmit}
                    className="rounded-2xl border border-gray-200 bg-white shadow-sm p-5 sm:p-7 space-y-6"
                >
                    {/* Judul & Kategori */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div className="md:col-span-2 space-y-1.5">
                            <label className="block text-sm font-semibold text-gray-800">
                                Judul Panduan / SOP / Tutorial <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                placeholder="Contoh: SOP Pengambilan Foto Narasumber & Angle Peliputan"
                                value={form.title}
                                onChange={(e) => setForm({ ...form, title: e.target.value })}
                                required
                                className="w-full h-10 px-3.5 text-sm rounded-xl border border-gray-200 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/20 outline-none transition"
                            />
                        </div>

                        <div className="space-y-1.5">
                            <label className="block text-sm font-semibold text-gray-800">
                                Kategori <span className="text-red-500">*</span>
                            </label>
                            <select
                                value={form.category}
                                onChange={(e) =>
                                    setForm({
                                        ...form,
                                        category: e.target.value as PanduanData['category'],
                                    })
                                }
                                className="w-full h-10 px-3 text-sm rounded-xl border border-gray-200 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/20 outline-none transition bg-white"
                            >
                                <option value="teknis">Panduan Teknis / Tutorial</option>
                                <option value="sop">Standar Operasional (SOP)</option>
                                <option value="pengumuman">Pengumuman Penting</option>
                                <option value="lainnya">Lainnya</option>
                            </select>
                        </div>
                    </div>

                    {/* Ringkasan Singkat */}
                    <div className="space-y-1.5">
                        <label className="block text-sm font-semibold text-gray-800">
                            Ringkasan Singkat (Excerpt)
                        </label>
                        <textarea
                            rows={2}
                            placeholder="Deskripsi singkat yang akan tampil di daftar panduan..."
                            value={form.excerpt}
                            onChange={(e) => setForm({ ...form, excerpt: e.target.value })}
                            className="w-full px-3.5 py-2 text-sm rounded-xl border border-gray-200 focus:border-sky-500 focus:ring-2 focus:ring-sky-500/20 outline-none transition"
                        />
                    </div>

                    {/* Gambar Sampul (Cover Image) */}
                    <div className="space-y-2 border-t border-gray-100 pt-4">
                        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-1">
                            <label className="block text-xs font-semibold text-gray-700">
                                Gambar Sampul / Banner (Opsional)
                            </label>
                            <span className="text-[11px] text-gray-500 font-medium">
                                Rasio baku: <strong className="text-sky-700 font-semibold">16:9</strong> (disarankan 1280 × 720 px)
                            </span>
                        </div>
                        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
                            {form.cover_image ? (
                                <div className="relative w-44 aspect-[16/9] rounded-xl overflow-hidden border border-gray-200 shadow-2xs group shrink-0 bg-gray-100">
                                    <img
                                        src={form.cover_image}
                                        alt="Sampul"
                                        className="w-full h-full object-cover object-center"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setForm({ ...form, cover_image: '' })}
                                        className="absolute top-1 right-1 p-1 bg-black/60 text-white rounded-md hover:bg-black/80 transition cursor-pointer"
                                        title="Hapus sampul"
                                    >
                                        <XMarkIcon className="w-3.5 h-3.5" />
                                    </button>
                                </div>
                            ) : (
                                <div className="w-44 aspect-[16/9] rounded-xl border border-dashed border-gray-300 bg-gray-50 flex flex-col items-center justify-center text-gray-400 shrink-0">
                                    <PhotoIcon className="w-6 h-6 stroke-1" />
                                    <span className="text-[10px] mt-1 font-medium text-gray-500">Format 16:9</span>
                                </div>
                            )}

                            <div className="space-y-2 flex-1 w-full">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/*"
                                    className="hidden"
                                    onChange={handleCoverUpload}
                                />
                                <div className="flex flex-wrap items-center gap-2">
                                    <Button
                                        variant="outline"
                                        size="sm"
                                        onPress={() => fileInputRef.current?.click()}
                                        isDisabled={uploadingCover}
                                    >
                                        <ArrowUpTrayIcon className="w-3.5 h-3.5" />
                                        <span>{uploadingCover ? 'Mengunggah...' : 'Pilih File Sampul'}</span>
                                    </Button>
                                    <span className="text-[11px] text-gray-400">
                                        Foto otomatis disesuaikan (fit center) agar tidak gepeng atau terdistorsi.
                                    </span>
                                </div>
                                <input
                                    type="url"
                                    placeholder="Atau tempel URL gambar: https://..."
                                    value={form.cover_image}
                                    onChange={(e) => setForm({ ...form, cover_image: e.target.value })}
                                    className="w-full h-9 px-3 text-xs rounded-xl border border-gray-200 focus:border-sky-500 outline-none"
                                />
                            </div>
                        </div>
                    </div>

                    {/* Pengaturan Pop-up Login & Status */}
                    <div className="border-t border-gray-100 pt-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
                        {/* Toggle Pop-up saat Login */}
                        <div className="bg-amber-50/70 border border-amber-200/80 rounded-xl p-4 space-y-2">
                            <div className="flex items-center justify-between">
                                <div className="flex items-center gap-2">
                                    <SparklesIcon className="w-4 h-4 text-amber-600" />
                                    <span className="text-sm font-semibold text-amber-950">
                                        Pop-up Modal Saat Login
                                    </span>
                                </div>
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={form.show_on_login}
                                        onChange={(e) =>
                                            setForm({ ...form, show_on_login: e.target.checked })
                                        }
                                        className="sr-only peer"
                                    />
                                    <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-amber-600"></div>
                                </label>
                            </div>
                            <p className="text-xs text-amber-900/80 leading-relaxed">
                                Jika diaktifkan, panduan/pengumuman ini akan otomatis tampil dalam jendela pop-up saat user membuka sistem setelah login, sampai mereka menekan &ldquo;Saya Sudah Membaca&rdquo;.
                            </p>
                        </div>

                        {/* Status Aktif & Prioritas */}
                        <div className="bg-gray-50 border border-gray-200 rounded-xl p-4 flex flex-col justify-between space-y-2">
                            <div className="flex items-center justify-between">
                                <span className="text-sm font-semibold text-gray-800">
                                    Status Publikasi
                                </span>
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={form.is_active}
                                        onChange={(e) =>
                                            setForm({ ...form, is_active: e.target.checked })
                                        }
                                        className="sr-only peer"
                                    />
                                    <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-sky-600"></div>
                                </label>
                            </div>
                            <div className="flex items-center justify-between text-xs text-gray-500 pt-1">
                                <span className="font-medium text-gray-700">{form.is_active ? 'Publikasi Aktif' : 'Draft (Belum Tampil)'}</span>
                                <div className="flex items-center gap-2">
                                    <span>Prioritas:</span>
                                    <input
                                        type="number"
                                        value={form.priority}
                                        onChange={(e) =>
                                            setForm({ ...form, priority: Number(e.target.value) })
                                        }
                                        className="w-16 h-8 px-2 text-xs border border-gray-300 rounded-lg bg-white text-center font-bold"
                                        title="Angka lebih tinggi ditampilkan lebih awal"
                                    />
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Rich Editor Konten Tutorial */}
                    <div className="space-y-2 border-t border-gray-100 pt-4">
                        <div className="flex items-center justify-between">
                            <label className="block text-sm font-semibold text-gray-800">
                                Konten Tutorial & Panduan Teknis <span className="text-red-500">*</span>
                            </label>
                            <span className="text-xs text-gray-500">
                                Gunakan tombol Foto di toolbar editor untuk mengunggah foto contoh/angle.
                            </span>
                        </div>

                        <RichEditor
                            content={form.content}
                            onChange={(html) => setForm((prev) => ({ ...prev, content: html }))}
                            minHeight="360px"
                        />
                    </div>

                    {/* Action footer */}
                    <div className="border-t border-gray-100 pt-4 flex justify-end gap-2.5">
                        <Button
                            variant="outline"
                            onPress={() => router.visit(isEdit ? `/panduan/${id}` : '/panduan')}
                        >
                            Batal
                        </Button>
                        <Button
                            variant="primary"
                            onPress={() => handleSubmit()}
                            isDisabled={saving}
                        >
                            <CheckIcon className="w-4 h-4" />
                            <span>{saving ? 'Menyimpan...' : 'Simpan'}</span>
                        </Button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
