import React, { useEffect, useRef } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faArrowLeft, faSave, faCamera, faImages, faTimes, faTag
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

// ========================================================================
// --- Komponen Utama: Gallery Create Page (Tema Biru, Input Sesuai Controller) ---
// ========================================================================

/**
 * Komponen untuk menambahkan item galeri (foto) baru.
 * @param {object} props
 * @param {object} props.auth
 * @param {object} props.errors - Errors validasi dari Laravel
 * @param {object} props.categoryOptions - Opsi kategori dari Controller
 */
export default function GalleryCreate({ auth, errors, categoryOptions }) {
    
    // Inisialisasi useForm disesuaikan dengan controller: title, category, image_file
    const { data, setData, post, processing, clearErrors, reset } = useForm({
        title: '',      // Judul/Deskripsi Foto (sesuai validasi controller)
        category: Object.keys(categoryOptions)[0] || '', // Kategori (default ke yang pertama)
        image_file: null, 
    });

    const imageRef = useRef(null);

    // --- Image Handlers & Cleanup ---

    const clearImage = () => {
        // Revoke existing object URL to free up memory
        let currentPreviewUrl = data.image_file ? URL.createObjectURL(data.image_file) : null;
        
        if (data.image_file && currentPreviewUrl) {
            URL.revokeObjectURL(currentPreviewUrl);
        }
        setData('image_file', null);
        if (imageRef.current) {
            imageRef.current.value = null;
        }
        clearErrors('image_file');
    };

    // Calculate preview URL
    const previewUrl = data.image_file ? URL.createObjectURL(data.image_file) : null;

    useEffect(() => {
        // Cleanup untuk URL Pratinjau saat komponen dilepas atau image_file berubah
        return () => {
            if (previewUrl) {
                URL.revokeObjectURL(previewUrl);
            }
        };
    }, [previewUrl]);

    // --- Form Handler ---

    const submit = (e) => {
        e.preventDefault();

        Swal.fire({
            title: 'Konfirmasi Simpan Foto Galeri',
            text: "Apakah Anda yakin ingin menyimpan foto ini ke galeri?",
            icon: 'question',
            showCancelButton: true,
            // DIUBAH KE WARNA BIRU
            confirmButtonColor: '#3B82F6', // blue-500
            cancelButtonColor: '#EF4444', // red-500
            confirmButtonText: 'Ya, Simpan',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                post(route('admin.kampus.galeri.store'), { 
                    onSuccess: () => {
                        reset(); 
                        clearImage(); // Pastikan state dan input file direset
                        Swal.fire('Berhasil!', 'Foto baru telah berhasil ditambahkan ke galeri.', 'success');
                    },
                    onError: (errors) => {
                        console.error("Gagal menyimpan foto galeri:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat menyimpan data. Periksa kembali input Anda.', 'error');
                    },
                    forceFormData: true, // Wajib untuk upload file
                });
            }
        });
    };
    
    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Tambah Foto Galeri Baru</h2>}
        >
            <Head title="Tambah Foto Galeri" />

            <div className="max-w-3xl mx-auto sm:px-6 lg:px-8 py-12">
                <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-8">
                    
                    <div className="flex justify-between items-center mb-6 border-b pb-4">
                        <h3 className="text-xl font-bold text-gray-800 flex items-center">
                            {/* Aksen Biru pada Ikon */}
                            <FontAwesomeIcon icon={faImages} className="mr-3 text-blue-600" />
                            Formulir Foto Galeri Baru
                        </h3>
                        <Link
                            href={route('admin.kampus.galeri.index')} 
                            className="inline-flex items-center px-4 py-2 bg-gray-200 border border-transparent rounded-lg font-semibold text-xs text-gray-700 uppercase tracking-widest hover:bg-gray-300 transition duration-150"
                        >
                            <FontAwesomeIcon icon={faArrowLeft} className="w-3 h-3 mr-2" />
                            Kembali ke Galeri
                        </Link>
                    </div>

                    <form onSubmit={submit} className="space-y-6">
                        
                        {/* 1. Judul Foto (TITLE) - Sesuai Controller */}
                        <div>
                            <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
                                Judul Foto <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="title"
                                type="text"
                                value={data.title}
                                onChange={(e) => setData('title', e.target.value)} 
                                className={`mt-1 block w-full border ${errors.title ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500 transition duration-150`}
                                required
                            />
                            {errors.title && <p className="mt-2 text-sm text-red-600">{errors.title}</p>}
                        </div>

                        {/* 2. Kategori (CATEGORY) - Sesuai Controller */}
                        <div>
                            <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                <FontAwesomeIcon icon={faTag} className="w-3 h-3 mr-2" />
                                Kategori <span className="text-red-500">*</span>
                            </label>
                            <select
                                id="category"
                                value={data.category}
                                onChange={(e) => setData('category', e.target.value)} 
                                className={`mt-1 block w-full border ${errors.category ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500 transition duration-150 appearance-none`}
                                required
                            >
                                {Object.entries(categoryOptions).map(([key, value]) => (
                                    <option key={key} value={key}>
                                        {value}
                                    </option>
                                ))}
                            </select>
                            {errors.category && <p className="mt-2 text-sm text-red-600">{errors.category}</p>}
                        </div>
                        
                        {/* 3. Unggah Gambar Utama (image_file) */}
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                <FontAwesomeIcon icon={faCamera} className="w-4 h-4 mr-2" />
                                Pilih Foto Galeri <span className="text-red-500">*</span>
                            </label>
                            <div className="flex items-center space-x-4">
                                <input
                                    ref={imageRef}
                                    id="image_file"
                                    type="file"
                                    onChange={(e) => setData('image_file', e.target.files[0])}
                                    className={`block w-full text-sm text-gray-900 border ${errors.image_file ? 'border-red-500' : 'border-gray-300'} rounded-lg cursor-pointer bg-gray-50 focus:outline-none p-2 transition duration-150`}
                                    accept="image/*"
                                    required={!data.image_file} 
                                />
                                {data.image_file && (
                                    <button
                                        type="button"
                                        onClick={clearImage}
                                        className="p-2 text-red-600 hover:text-red-800 transition duration-150 rounded-full"
                                        aria-label="Hapus Gambar"
                                    >
                                        <FontAwesomeIcon icon={faTimes} className="w-5 h-5" />
                                    </button>
                                )}
                            </div>
                            {errors.image_file && <p className="mt-2 text-sm text-red-600">{errors.image_file}</p>}

                            {/* Pratinjau Gambar */}
                            {previewUrl && (
                                <div className="mt-4 p-2 border border-gray-200 rounded-lg bg-gray-50">
                                    <p className="text-xs text-gray-500 mb-2">Pratinjau Foto:</p>
                                    <img 
                                        src={previewUrl} 
                                        alt="Pratinjau Foto Galeri" 
                                        className="w-full max-h-64 object-cover rounded-lg shadow-md"
                                    />
                                </div>
                            )}
                        </div>

                        {/* Tombol Aksi */}
                        <div className="flex justify-end pt-4 border-t mt-6">
                            <button
                                type="submit"
                                disabled={processing}
                                className={`inline-flex items-center px-6 py-3 border border-transparent rounded-lg font-semibold text-sm uppercase tracking-widest transition ease-in-out duration-150 shadow-md justify-center ${
                                    // Aksen Biru pada tombol simpan
                                    processing 
                                    ? 'bg-blue-400 cursor-not-allowed' 
                                    : 'bg-blue-600 text-white hover:bg-blue-700 active:bg-blue-900 focus:outline-none focus:border-blue-900 focus:ring ring-blue-300'
                                }`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Menyimpan...' : 'Simpan Foto'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}