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, faImage, faNewspaper, faCalendarDay, faTimes, faBug
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';

export default function NewsCreate({ auth, errors, categoryOptions = {} }) {
    
    const { data, setData, post, processing, clearErrors, reset } = useForm({
        excerpt: '', 
        content: '', 
        category: '', 
        published_at: '', 
        image_file: null, 
    });

    const imageRef = useRef(null);

    // --- Image Handlers & Cleanup ---
    const clearImage = () => {
        setData('image_file', null);
        if (imageRef.current) {
            imageRef.current.value = null;
        }
        clearErrors('image_file');
    };

    useEffect(() => {
        return () => {
            if (data.image_file && URL.createObjectURL(data.image_file)) {
                URL.revokeObjectURL(URL.createObjectURL(data.image_file));
            }
        };
    }, [data.image_file]);

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

    // --- Form Handlers ---
    const submit = (e) => {
        e.preventDefault();

        Swal.fire({
            title: 'Konfirmasi Simpan Berita',
            text: "Apakah Anda yakin data berita sudah benar dan ingin disimpan?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10B981', 
            cancelButtonColor: '#EF4444', 
            confirmButtonText: 'Ya, Simpan',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                post(route('admin.kampus.berita.store'), { 
                    onSuccess: () => {
                        reset(); 
                        setData('category', ''); 
                        if (imageRef.current) {
                            imageRef.current.value = null;
                        }
                        Swal.fire('Berhasil!', 'Berita baru telah berhasil ditambahkan.', 'success');
                    },
                    onError: (errors) => {
                        console.error("Gagal menyimpan berita:", errors);
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat menyimpan data. Periksa kembali input Anda.', 'error');
                    },
                    forceFormData: true, 
                });
            }
        });
    };
    
    const isCategoryEmpty = Object.keys(categoryOptions).length === 0;

    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Tambah Berita Baru</h2>}
        >
            <Head title="Tambah Berita" />

            <div className="max-w-4xl mx-auto sm:px-6 lg:px-8 py-12">
                <div className="bg-white overflow-hidden shadow-xl sm:rounded-xl p-8">

                    {/* --- DEBUGGING SECTION --- */}
                    {isCategoryEmpty && (
                        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                            <strong className="font-bold flex items-center">
                                <FontAwesomeIcon icon={faBug} className="mr-2" /> DEBUG ALERT:
                            </strong>
                            <span className="block sm:inline"> Kategori kosong. Pastikan Controller (NewsController) mengirim data.</span>
                        </div>
                    )}
                    {!isCategoryEmpty && (
                        <div className="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded relative mb-4 text-xs">
                            <strong className="font-bold">DATA KATEGORI DITERIMA: </strong>
                            {JSON.stringify(categoryOptions)}
                        </div>
                    )}
                    {/* --- END DEBUGGING SECTION --- */}
                    
                    <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">
                            <FontAwesomeIcon icon={faNewspaper} className="mr-3 text-emerald-600" />
                            Formulir Berita Baru
                        </h3>
                        <Link
                            href={route('admin.kampus.berita.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 Daftar
                        </Link>
                    </div>

                    <form onSubmit={submit} className="space-y-6">
                        
                        {/* 1. Judul/Ringkasan Berita (Excerpt) */}
                        <div>
                            <label htmlFor="excerpt" className="block text-sm font-medium text-gray-700 mb-1">
                                Judul / Ringkasan (Max 500 Karakter) <span className="text-red-500">*</span>
                            </label>
                            <input
                                id="excerpt"
                                type="text"
                                value={data.excerpt}
                                onChange={(e) => setData('excerpt', e.target.value)} 
                                className={`mt-1 block w-full border ${errors.excerpt ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                required
                            />
                            {errors.excerpt && <p className="mt-2 text-sm text-red-600">{errors.excerpt}</p>}
                        </div>
                        
                        {/* Grup 2 Kolom: Kategori & Tanggal Publikasi */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            {/* 2. Kategori */}
                            <div>
                                <label htmlFor="category" className="block text-sm font-medium text-gray-700 mb-1">
                                    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-emerald-500 focus:border-emerald-500 transition duration-150`}
                                    required
                                >
                                    <option value="" disabled>--- Pilih Kategori ---</option>
                                    {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. Tanggal Publikasi */}
                            <div>
                                <label htmlFor="published_at" className="block text-sm font-medium text-gray-700 mb-1 flex items-center">
                                    <FontAwesomeIcon icon={faCalendarDay} className="w-4 h-4 mr-2" />
                                    Tanggal Publikasi (Kosongkan untuk Draft)
                                </label>
                                <input
                                    id="published_at"
                                    type="date"
                                    value={data.published_at || ''}
                                    onChange={(e) => setData('published_at', e.target.value)}
                                    className={`mt-1 block w-full border ${errors.published_at ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                />
                                {errors.published_at && <p className="mt-2 text-sm text-red-600">{errors.published_at}</p>}
                            </div>

                        </div>
                        
                        {/* 4. Isi Berita (Content) */}
                        <div>
                            <label htmlFor="content" className="block text-sm font-medium text-gray-700 mb-1">
                                Isi Berita <span className="text-red-500">*</span>
                            </label>
                            <textarea
                                id="content"
                                value={data.content}
                                onChange={(e) => setData('content', e.target.value)}
                                rows="6" 
                                className={`mt-1 block w-full border ${errors.content ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                                required
                            />
                            {errors.content && <p className="mt-2 text-sm text-red-600">{errors.content}</p>}
                        </div>

                        {/* 5. Unggah Gambar Utama */}
                        <div>
                            <label htmlFor="image_file" className="block text-sm font-medium text-gray-700 mb-1">
                                Gambar Utama
                            </label>
                            <input
                                type="file"
                                id="image_file"
                                ref={imageRef}
                                onChange={(e) => setData('image_file', e.target.files[0])}
                                accept="image/*"
                                className={`mt-1 block w-full border ${errors.image_file ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-emerald-500 focus:border-emerald-500 transition duration-150`}
                            />
                            {previewUrl && (
                                <div className="mt-4">
                                    <img src={previewUrl} alt="Preview" className="max-w-full h-auto" />
                                </div>
                            )}
                            {errors.image_file && <p className="mt-2 text-sm text-red-600">{errors.image_file}</p>}
                        </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 ${
                                    processing ? 'bg-emerald-400 cursor-not-allowed' : 'bg-emerald-600 text-white hover:bg-emerald-700 active:bg-emerald-900 focus:outline-none focus:border-emerald-900 focus:ring ring-emerald-300'
                                }`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Menyimpan...' : 'Simpan Berita'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}
