import React, { useMemo, useEffect } from 'react';
import AdminKampusLayout from '@/Layouts/AdminKampusLayout';
import { Head, Link, useForm } from '@inertiajs/react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
    faArrowLeft, faSave, faUniversity, faMoneyBillWave, faGraduationCap, faList, faDollarSign, faEdit
} from '@fortawesome/free-solid-svg-icons';
import Swal from 'sweetalert2';
import InputError from '@/Components/InputError';

// --- Konfigurasi Jenjang Pendidikan Default ---
const DEGREE_LEVELS = ['S1', 'D3', 'S2', 'D4'];

// ========================================================================
// --- Komponen Pendaftaran Biaya Dinamis ---
// (Sama persis dengan Create.jsx)
// ========================================================================

/**
 * Komponen untuk mengelola input biaya pendaftaran per jenjang.
 */
function RegistrationFeeInput({ data, setData, errors }) {
    // Handler untuk memperbarui biaya pendaftaran berdasarkan jenjang
    const handleFeeChange = (level, value) => {
        // Hanya menerima input digit (angka)
        const numericValue = value.replace(/\D/g, ''); 
        setData('registration_fees', {
            ...data.registration_fees,
            [level]: String(numericValue) // Pastikan itu string
        });
    };

    /**
     * Helper untuk memformat angka menjadi format Rupiah (tanpa symbol Rp)
     */
    const formatRupiah = (number) => {
        if (!number) return ''; // Mengembalikan string kosong untuk input
        // Hapus karakter non-digit, lalu konversi ke string
        const numberString = String(number).replace(/\D/g, ''); 
        
        // Tambahkan pemisah ribuan
        return new Intl.NumberFormat('id-ID').format(Number(numberString));
    };

    // Fungsi untuk mendapatkan nilai non-format dari state
    const getRawValue = (level) => {
        // Hanya ambil nilai angka (string) dari state
        return data.registration_fees[level] || '';
    };

    return (
        <div className="space-y-4">
            <h5 className="font-medium text-gray-800 flex items-center mb-2">
                <FontAwesomeIcon icon={faGraduationCap} className="mr-2 text-indigo-500" />
                Biaya Pendaftaran per Jenjang <span className="text-red-500 ml-1">*</span>
            </h5>
            <p className="text-sm text-gray-500 mb-4">
                Masukkan biaya pendaftaran (hanya angka) untuk setiap jenjang yang ditawarkan.
                <span className="font-semibold text-green-700"> Minimal satu jenjang harus diisi</span> agar Nama Jurusan bisa diinput.
            </p>
            <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
                {DEGREE_LEVELS.map(level => (
                    <div key={level} className="p-3 bg-gray-50 border border-gray-200 rounded-lg">
                        <label htmlFor={`fee_${level}`} className="block text-xs font-semibold text-gray-700 mb-1">
                            Jenjang {level}
                        </label>
                        <div className="flex items-center mt-1">
                            <span className="text-sm font-medium text-gray-600 mr-2">Rp</span>
                            <input
                                id={`fee_${level}`}
                                type="text"
                                // Tampilkan nilai yang di-format saat tidak fokus
                                value={getRawValue(level)}
                                onChange={(e) => handleFeeChange(level, e.target.value)}
                                onBlur={(e) => e.target.value = formatRupiah(getRawValue(level))}
                                onFocus={(e) => e.target.value = getRawValue(level)}
                                placeholder="0"
                                className={`block w-full border border-gray-300 rounded-lg shadow-sm p-2 text-sm focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 text-right`}
                            />
                        </div>
                    </div>
                ))}
            </div>

            {/* Menampilkan error registration_fees jika ada */}
            {errors['registration_fees'] && <InputError message={errors['registration_fees']} className="mt-2" />}
            {DEGREE_LEVELS.map(level => errors[`registration_fees.${level}`] && (
                <InputError key={level} message={`Jenjang ${level}: ${errors[`registration_fees.${level}`]}`} className="mt-2" />
            ))}
        </div>
    );
}

// ========================================================================
// --- Komponen Utama: Jurusan Edit Page ---
// ========================================================================

/**
 * @param {object} props
 * @param {object} props.auth
 * @param {object} props.errors - Errors validasi dari Laravel
 * @param {array} props.program_options - Pilihan program kuliah
 * @param {object} props.jurusan - Data model Jurusan yang akan diedit
 */
export default function JurusanEdit({ auth, errors, program_options, jurusan }) { 
    
    // --- PENYESUAIAN DATA LAMA UNTUK useForm ---
    
    // 1. Memisahkan 'name' (misal: S1 Manajemen) menjadi 'degree_level' dan 'prodi_name'
    const nameParts = jurusan.name.split(' ');
    // degree_level adalah bagian pertama (misal: 'S1')
    const initialDegreeLevel = nameParts[0] || DEGREE_LEVELS[0]; 
    // prodi_name adalah sisa bagiannya (misal: 'Manajemen')
    const initialProdiName = nameParts.slice(1).join(' ') || '';

    // 2. Memastikan registration_fees adalah objek dengan semua key DEGREE_LEVELS
    const initialRegistrationFees = DEGREE_LEVELS.reduce((acc, level) => {
        // Ambil nilai dari data lama (jurusan.registration_fees), atau string kosong
        acc[level] = jurusan.registration_fees?.[level] || '';
        return acc;
    }, {});
    
    // 3. Mengambil nilai biaya_pendaftaran aktif lama
    const initialActiveFee = jurusan.biaya_pendaftaran || initialRegistrationFees[initialDegreeLevel] || '';

    // ------------------------------------------

    const { data, setData, put, processing } = useForm({
        // Field yang digunakan untuk membentuk 'name'
        degree_level: initialDegreeLevel, 
        prodi_name: initialProdiName, 
        
        // Field lain dari data Jurusan
        program_kuliah: jurusan.program_kuliah || program_options[0] || '', 
        registration_fees: initialRegistrationFees,
        initial_fee: jurusan.initial_fee || '', 
        biaya_awal_description: jurusan.biaya_awal_description || 'Termasuk Angsuran ke-1, Uang Masuk, dan Kartu Tanda Mahasiswa (KTM)', 
        normal_monthly_fee: jurusan.normal_monthly_fee || '', 
        promo_monthly_fee: jurusan.promo_monthly_fee || '', 
        is_active: jurusan.is_active,
        
        // Field untuk menyimpan Biaya Pendaftaran aktif tunggal
        active_registration_fee: initialActiveFee, 
    });

    // --- LOGIKA OTOMATISASI & VALIDASI FRONT-END ---

    // 1. Cek apakah minimal satu biaya pendaftaran sudah diisi
    const isAnyFeeFilled = useMemo(() => {
        return Object.values(data.registration_fees).some(fee => fee && fee.toString().trim() !== '' && fee.toString() !== '0');
    }, [data.registration_fees]);

    // 2. Efek untuk memperbarui active_registration_fee berdasarkan degree_level
    useEffect(() => {
        // Ambil nilai biaya dari registration_fees berdasarkan degree_level yang dipilih saat ini
        const fee = data.registration_fees[data.degree_level] || '';
        // Perbarui state active_registration_fee
        setData('active_registration_fee', fee);
    }, [data.degree_level, data.registration_fees, setData]); // Bergantung pada perubahan degree_level dan seluruh array registration_fees

    // --- Form Handlers ---

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

        if (!isAnyFeeFilled) {
            Swal.fire('Perhatian!', 'Anda harus mengisi minimal satu Biaya Pendaftaran per Jenjang sebelum menyimpan.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Konfirmasi Ubah',
            text: "Apakah Anda yakin ingin menyimpan perubahan data jurusan/biaya kuliah ini?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#4F46E5', 
            cancelButtonColor: '#EF4444',  
            confirmButtonText: 'Ya, Simpan Perubahan',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                // Gunakan PUT/PATCH method untuk update
                put(route('admin.kampus.jurusan.update', jurusan.id), {
                    onSuccess: () => {
                        Swal.fire('Berhasil!', 'Jurusan telah berhasil diubah.', 'success');
                    },
                    onError: (errors) => {
                        // Jika ada error validasi dari Laravel, Swal akan muncul
                        Swal.fire('Gagal!', 'Terjadi kesalahan saat menyimpan data. Periksa kembali input Anda.', 'error');
                    },
                });
            }
        });
    };

    /**
     * Mengatur perubahan input bertipe angka (menghapus karakter non-digit).
     */
    const handleNumberChange = (e, field) => {
        const value = e.target.value.replace(/\D/g, ''); 
        setData(field, value);
    };

    /**
     * Helper untuk memformat angka menjadi format Rupiah (tanpa symbol Rp)
     */
    const formatRupiah = (number) => {
        if (!number || number.toString().trim() === '') return '0';
        // Hapus karakter non-digit, lalu konversi ke string
        const numberString = String(number).replace(/\D/g, ''); 
        
        // Tambahkan pemisah ribuan
        return new Intl.NumberFormat('id-ID').format(Number(numberString));
    };

    return (
        <AdminKampusLayout
            user={auth.user}
            header={<h2 className="font-semibold text-xl text-gray-800 leading-tight">Ubah Jurusan: {jurusan.name}</h2>}
        >
            <Head title={`Ubah Jurusan: ${jurusan.name}`} />

            <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">

                    {/* Header dan Tombol Kembali */}
                    <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={faEdit} className="mr-3 text-indigo-600" />
                            Formulir Ubah Jurusan & Biaya Kuliah
                        </h3>
                        <Link
                            href={route('admin.kampus.jurusan.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. Program Kuliah (Paling Atas) */}
                        <div className="mb-6 pb-6 border-b">
                            <label htmlFor="program_kuliah" className="block text-sm font-medium text-gray-700 mb-1">
                                Program Kuliah <span className="text-red-500">*</span>
                            </label>
                            <select
                                id="program_kuliah"
                                value={data.program_kuliah}
                                onChange={(e) => setData('program_kuliah', e.target.value)}
                                className={`mt-1 block w-full border ${errors.program_kuliah ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                required
                            >
                                {program_options.map(option => (
                                    <option key={option} value={option}>{option}</option>
                                ))}
                            </select>
                            <InputError message={errors.program_kuliah} className="mt-2" />
                        </div>
                        
                        {/* 2. Biaya Pendaftaran per Jenjang (Display Normal) */}
                        <div className="border-b pb-6">
                            <RegistrationFeeInput 
                                data={data} 
                                setData={setData} 
                                errors={errors}
                            />
                        </div>

                        {/* 3. Nama Program Studi & Biaya Pendaftaran AKTIF (HIDDEN VISUAL) */}
                        <div className="border-b pb-6">
                            
                            {/* Biaya Pendaftaran Aktif (DISOROKKAN dari Tampilan, hanya menampilkan pesan) */}
                            <div className="mb-4">

                                {/* HIDDEN INPUT untuk mengirim nilai active_registration_fee ke backend sebagai biaya_pendaftaran */}
                                {/* Catatan: Ini digunakan untuk memetakan di controller. */}
                                <input 
                                    type="hidden" 
                                    name="biaya_pendaftaran" 
                                    value={data.active_registration_fee} 
                                />
                                
                            </div>
                            
                            <label className={`block text-sm font-medium mb-1 ${!isAnyFeeFilled ? 'text-gray-500' : 'text-gray-700'}`}>
                                Nama Program Studi <span className="text-red-500">*</span>
                            </label>

                            <div className="flex space-x-3 mt-4">
                                {/* Dropdown Degree Level */}
                                <div className="w-1/3">
                                    <select
                                        id="degree_level"
                                        value={data.degree_level}
                                        onChange={(e) => setData('degree_level', e.target.value)}
                                        disabled={!isAnyFeeFilled || processing}
                                        className={`mt-1 block w-full border ${errors.degree_level ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 ${!isAnyFeeFilled ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                                        required
                                    >
                                        {DEGREE_LEVELS.map(level => (
                                            <option key={level} value={level}>{level}</option>
                                        ))}
                                    </select>
                                </div>
                                
                                {/* Input Nama Prograam Studi */}
                                <div className="w-2/3">
                                    <input
                                        id="prodi_name"
                                        type="text"
                                        value={data.prodi_name}
                                        onChange={(e) => setData('prodi_name', e.target.value)} 
                                        placeholder="Contoh: Ilmu Komputer atau Manajemen"
                                        disabled={!isAnyFeeFilled || processing} // Disabled jika biaya belum terisi
                                        className={`mt-1 block w-full border ${errors.prodi_name ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 ${!isAnyFeeFilled ? 'bg-gray-100 cursor-not-allowed' : ''}`}
                                        required={isAnyFeeFilled} // Wajib diisi jika sudah aktif
                                    />
                                </div>
                            </div>
                            
                            {/* Tampilkan pesan peringatan jika disabled */}
                            {!isAnyFeeFilled && (
                                <p className="mt-2 text-sm text-yellow-600 bg-yellow-50 p-2 rounded-lg">
                                    <FontAwesomeIcon icon={faList} className="mr-1" />
                                    Isi minimal satu Biaya Pendaftaran di atas untuk mengaktifkan input Nama Program Studi.
                                </p>
                            )}

                            {/* Error yang mungkin datang dari backend untuk field 'name' atau 'prodi_name' */}
                            {errors.name && <InputError message={errors.name} className="mt-2" />}
                            {errors.prodi_name && <InputError message={errors.prodi_name} className="mt-2" />}
                            {errors.degree_level && <InputError message={errors.degree_level} className="mt-2" />}
                        </div>
                        
                        {/* 4. Detail Biaya Angsuran */}
                        <div className="border-t pt-6">
                            <h4 className="text-lg font-semibold text-gray-800 mb-6 flex items-center">
                                <FontAwesomeIcon icon={faMoneyBillWave} className="mr-2 text-green-600" />
                                Detail Biaya Angsuran
                            </h4>
                            <div className="grid grid-cols-1 gap-6">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                    {/* Biaya Awal */}
                                    <div>
                                        <label htmlFor="initial_fee" className="block text-sm font-medium text-gray-700 mb-1">
                                            Biaya Awal (Uang Pangkal/Angsuran Pertama) (Rp) <span className="text-red-500">*</span>
                                        </label>
                                        <input
                                            id="initial_fee"
                                            type="text" 
                                            min="0"
                                            value={formatRupiah(data.initial_fee)}
                                            onChange={(e) => handleNumberChange(e, 'initial_fee')} 
                                            placeholder="Contoh: 700.000"
                                            className={`mt-1 block w-full border ${errors.initial_fee ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                            required
                                        />
                                        <InputError message={errors.initial_fee} className="mt-2" />
                                    </div>

                                    {/* Angsuran Normal Bulanan */}
                                    <div>
                                        <label htmlFor="normal_monthly_fee" className="block text-sm font-medium text-gray-700 mb-1">
                                            Angsuran Normal Bulanan (Rp) <span className="text-red-500">*</span>
                                        </label>
                                        <input
                                            id="normal_monthly_fee"
                                            type="text" 
                                            min="0"
                                            value={formatRupiah(data.normal_monthly_fee)}
                                            onChange={(e) => handleNumberChange(e, 'normal_monthly_fee')} 
                                            placeholder="Contoh: 800.000"
                                            className={`mt-1 block w-full border ${errors.normal_monthly_fee ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                            required
                                        />
                                        <InputError message={errors.normal_monthly_fee} className="mt-2" />
                                    </div>

                                    {/* Angsuran Promo Bulanan (Opsional) */}
                                    <div className="md:col-span-2">
                                        <label htmlFor="promo_monthly_fee" className="block text-sm font-medium text-gray-700 mb-1">
                                            Angsuran Promo Bulanan (Rp) (Opsional)
                                        </label>
                                        <input
                                            id="promo_monthly_fee"
                                            type="text" 
                                            min="0"
                                            value={formatRupiah(data.promo_monthly_fee)}
                                            onChange={(e) => handleNumberChange(e, 'promo_monthly_fee')} 
                                            placeholder="Contoh: 500.000 (Kosongkan jika tidak ada promo)"
                                            className={`mt-1 block w-full border ${errors.promo_monthly_fee ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                        />
                                        <InputError message={errors.promo_monthly_fee} className="mt-2" />
                                    </div>
                                </div>

                                {/* Deskripsi Biaya Awal */}
                                <div className="md:col-span-2"> 
                                    <label htmlFor="biaya_awal_description" className="block text-sm font-medium text-gray-700 mb-1">
                                        Deskripsi Biaya Awal (Singkat)
                                    </label>
                                    <input
                                        id="biaya_awal_description"
                                        type="text"
                                        value={data.biaya_awal_description}
                                        onChange={(e) => setData('biaya_awal_description', e.target.value)} 
                                        placeholder="Contoh: Termasuk Angsuran ke-1, Uang Masuk, dan KTM"
                                        className={`mt-1 block w-full border ${errors.biaya_awal_description ? 'border-red-500' : 'border-gray-300'} rounded-lg shadow-sm p-3 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150`}
                                    />
                                    <InputError message={errors.biaya_awal_description} className="mt-2" />
                                </div>
                            </div>
                        </div>

                        {/* 5. Status Aktif */}
                        <div className="flex items-center pt-4 border-t">
                            <input
                                id="is_active"
                                type="checkbox"
                                checked={data.is_active}
                                onChange={(e) => setData('is_active', e.target.checked)}
                                className="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
                            />
                            <label htmlFor="is_active" className="ml-2 block text-sm font-medium text-gray-700">
                                Aktif (Tampilkan di halaman Biaya Kuliah)
                            </label>
                            <InputError message={errors.is_active} className="mt-2" />
                        </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-indigo-400 cursor-not-allowed' : 'bg-indigo-600 text-white hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300'
                                }`}
                            >
                                <FontAwesomeIcon icon={faSave} className="w-4 h-4 mr-2" />
                                {processing ? 'Menyimpan...' : 'Simpan Perubahan'}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </AdminKampusLayout>
    );
}