import { Head, Link, useForm } from '@inertiajs/react';
import {
    Activity, Flame, Plus, ClipboardCheck, Droplet,
    Home, User, LogOut, Utensils, X, Trash2,
    ChevronLeft, ChevronRight, CalendarDays, Beef, Wheat,
    Lock, Unlock, ShieldCheck
} from 'lucide-react';
import { useState, useMemo } from 'react';
import toast, { Toaster } from 'react-hot-toast'; // <-- TAMBAHAN IMPORT UNTUK NOTIFIKASI

export default function InputAsupan({ auth, foods = [], asupans = [] }) {
    const [showProfileMenu, setShowProfileMenu] = useState(false);
    const [foodQuery, setFoodQuery] = useState('');
    const [showFoodSuggestions, setShowFoodSuggestions] = useState(false);

    // --- FITUR BARU: Deteksi sumber makanan (Database vs Manual) ---
    const [isFromDatabase, setIsFromDatabase] = useState(false);

    // --- STANDAR TARGET HARIAN ---
    const TARGET_KALORI = 1800;
    const BATAS_NATRIUM = 2000;
    const TARGET_PROTEIN = 60; // Gram
    const TARGET_KARBO = 250;  // Gram

    const timeLabels = {
        pagi: 'Sarapan',
        snack_pagi: 'Snack Pagi',
        siang: 'Makan Siang',
        snack_sore: 'Snack Sore',
        malam: 'Makan Malam'
    };

    const foodOptions = foods;

    const [meals, setMeals] = useState(asupans);
    const today = new Date().toLocaleDateString('en-CA');
    const [selectedDate, setSelectedDate] = useState(today);

    const [isModalOpen, setIsModalOpen] = useState(false);

    const { data, setData, post, processing, reset } = useForm({
        waktu: 'pagi',
        tanggal: selectedDate,
        nama_makanan: '',
        porsi: '1 Porsi',
        kalori: '',
        natrium: '',
        protein: '',
        karbo: ''
    });

    const filteredMeals = useMemo(() => {
        return meals.filter(food => food.tanggal === selectedDate);
    }, [meals, selectedDate]);

    const totals = useMemo(() => {
        let kal = 0, nat = 0, pro = 0, kar = 0;
        filteredMeals.forEach(food => {
            kal += Number(food.kalori) || 0;
            nat += Number(food.natrium) || 0;
            pro += Number(food.protein) || 0;
            kar += Number(food.karbo) || 0;
        });
        return { kalori: kal, natrium: nat, protein: pro, karbo: kar };
    }, [filteredMeals]);

    const pctKalori = Math.min((totals.kalori / TARGET_KALORI) * 100, 100);
    const pctNatrium = Math.min((totals.natrium / BATAS_NATRIUM) * 100, 100);
    const pctProtein = Math.min((totals.protein / TARGET_PROTEIN) * 100, 100);
    const pctKarbo = Math.min((totals.karbo / TARGET_KARBO) * 100, 100);

    const filteredFoodOptions = useMemo(() => {
        const normalizedQuery = foodQuery.trim().toLowerCase();
        if (!normalizedQuery) return foodOptions;
        return foodOptions.filter(option => option.nama_bahan.toLowerCase().includes(normalizedQuery));
    }, [foodQuery, foodOptions]);

    const allFoodsList = useMemo(() => {
        return filteredMeals
            .map(food => ({ ...food, labelWaktu: timeLabels[food.waktu] || 'Lainnya' }))
            .sort((a, b) => {
                const order = Object.keys(timeLabels);
                return order.indexOf(a.waktu) - order.indexOf(b.waktu);
            });
    }, [filteredMeals]);

    const changeDate = (days) => {
        const currentDate = new Date(selectedDate);
        currentDate.setDate(currentDate.getDate() + days);
        const newDateString = currentDate.toLocaleDateString('en-CA');
        setSelectedDate(newDateString);
        setData('tanggal', newDateString);
    };

    const formatDateIndo = (dateStr) => {
        const options = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
        return new Date(dateStr).toLocaleDateString('id-ID', options);
    };

    const openAddModal = () => {
        setIsModalOpen(true);
        setIsFromDatabase(false);
        setFoodQuery('');
        reset('nama_makanan', 'porsi', 'kalori', 'natrium', 'protein', 'karbo');
    };

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

        post(route('input.asupan.store'), {
            preserveScroll: true,
            onSuccess: () => {
                setMeals(prev => ([...prev, {
                    id: Date.now(),
                    tanggal: data.tanggal,
                    waktu: data.waktu,
                    nama_makanan: data.nama_makanan,
                    porsi: data.porsi,
                    kalori: data.kalori,
                    natrium: data.natrium,
                    protein: data.protein || 0,
                    karbo: data.karbo || 0,
                    labelWaktu: timeLabels[data.waktu] || 'Lainnya'
                }]));

                // --- TAMBAHAN PESAN SUKSES & EMAIL ---
                toast.success('Data asupan berhasil dicatat! Rincian telah dikirim ke email Anda.');

                reset('nama_makanan', 'porsi', 'kalori', 'natrium', 'protein', 'karbo');
                setFoodQuery('');
                setIsFromDatabase(false);
                setIsModalOpen(false);
            },
            onError: () => {
                toast.error('Gagal menyimpan asupan. Silakan coba lagi.');
            }
        });
    };

    const handleDeleteFood = (foodId) => {
        setMeals(prev => prev.filter(f => f.id !== foodId));
        toast.success('Data asupan berhasil dihapus.');
    };

    return (
        <div className={`min-h-screen bg-[#F8FBF8] font-sans text-slate-800 pb-24 md:pb-0 relative ${isModalOpen ? 'h-screen overflow-hidden' : ''}`}>
            <Head title="Catat Asupan" />

            {/* --- KOMPONEN TOAST NOTIFIKASI --- */}
            <Toaster position="top-center" toastOptions={{ style: { borderRadius: '1rem', background: '#333', color: '#fff', fontWeight: 'bold' } }} />

            {/* --- NAVBAR ATAS (Desktop) --- */}
            <nav className="fixed top-0 w-full bg-[#F8FBF8]/90 backdrop-blur-md z-40 py-4 border-b border-[#E5EFE9]">
                <div className="max-w-7xl mx-auto px-6 lg:px-8">
                    <div className="flex justify-between items-center">
                        <div className="flex-shrink-0 flex items-center gap-2">
                            <div className="w-8 h-8 rounded-xl bg-gradient-to-br from-[#EA580C] to-[#145C33] flex items-center justify-center text-white font-bold">H</div>
                            <span className="font-bold text-xl text-emerald-900 tracking-tight hidden sm:block">HiperDiet</span>
                        </div>

                        <div className="hidden md:flex space-x-8 items-center">
                            <Link href={route('dashboard')} className="text-slate-500 hover:text-[#EA580C] font-semibold transition text-sm">Beranda</Link>
                            <Link href={route('input.asupan')} className="text-[#EA580C] font-bold border-b-2 border-[#EA580C] pb-1 text-sm">Riwayat Makan</Link>
                            <Link href={route('kuis')} className="text-slate-500 hover:text-[#EA580C] font-semibold transition text-sm">Kuis Kepatuhan</Link>
                        </div>

                        <div className="relative">
                            <button onClick={() => setShowProfileMenu(!showProfileMenu)} className="flex items-center gap-3 bg-white border border-[#E5EFE9] pl-3 pr-4 py-2 rounded-full hover:shadow-md transition">
                                <div className="w-8 h-8 bg-[#145C33] text-white rounded-full flex items-center justify-center font-bold text-sm">
                                    {auth?.user?.name ? auth.user.name.charAt(0) : 'U'}
                                </div>
                                <span className="text-sm font-bold text-slate-700 hidden sm:block">{auth?.user?.name}</span>
                            </button>
                            {showProfileMenu && (
                                <div className="absolute right-0 mt-2 w-48 bg-white rounded-2xl shadow-xl border border-slate-100 py-2 z-50">
                                    <Link href={route('profile.edit')} className="flex items-center gap-2 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 hover:text-[#145C33]"><User size={16} /> Profil Saya</Link>
                                    <Link href={route('logout')} method="post" as="button" className="flex w-full items-center gap-2 px-4 py-2 text-sm text-red-600 hover:bg-red-50"><LogOut size={16} /> Keluar</Link>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </nav>

            {/* --- BOTTOM NAVIGATION BAR (Khusus Mobile) --- */}
            <div className="md:hidden fixed bottom-0 w-full bg-white rounded-t-3xl shadow-[0_-10px_40px_rgba(0,0,0,0.08)] z-40 px-6 py-3 pb-safe border-t border-slate-100">
                <div className="flex justify-between items-center text-[10px] font-bold text-slate-400 relative">
                    <Link href={route('dashboard')} className={`flex flex-col items-center gap-1 w-12 ${route().current('dashboard') ? 'text-[#145C33]' : ''}`}>
                        <Home size={24} className={route().current('dashboard') ? 'text-[#145C33]' : ''} />
                        <span>Home</span>
                    </Link>
                    <Link href={route('input.asupan')} className={`flex flex-col items-center gap-1 w-12 mr-6 ${route().current('input.asupan') ? 'text-[#145C33]' : ''}`}>
                        <Activity size={24} className={route().current('input.asupan') ? 'text-[#145C33]' : ''} />
                        <span>Riwayat</span>
                    </Link>
                    <div className="absolute left-1/2 -translate-x-1/2 -top-6">
                        <button onClick={openAddModal} className="bg-gradient-to-br from-[#EA580C] to-[#c24100] text-white w-14 h-14 rounded-full flex items-center justify-center shadow-lg shadow-orange-500/30 transform hover:-translate-y-1 transition border-4 border-[#F8FBF8]">
                            <Plus size={28} />
                        </button>
                    </div>
                    <Link href={route('kuis')} className={`flex flex-col items-center gap-1 w-12 ml-6 ${route().current('kuis') ? 'text-[#145C33]' : ''}`}>
                        <ClipboardCheck size={24} className={route().current('kuis') ? 'text-[#145C33]' : ''} />
                        <span>Kuis</span>
                    </Link>
                    <Link href={route('profile.edit')} className={`flex flex-col items-center gap-1 w-12 ${route().current('profile.edit') ? 'text-[#145C33]' : ''}`}>
                        <User size={24} className={route().current('profile.edit') ? 'text-[#145C33]' : ''} />
                        <span>Profil</span>
                    </Link>
                </div>
            </div>

            {/* --- KONTEN UTAMA --- */}
            <main className="pt-28 md:pt-32 max-w-5xl mx-auto px-4 lg:px-8 space-y-6">

                <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
                    <div>
                        <h2 className="text-2xl md:text-3xl font-extrabold text-slate-900 tracking-tight">Catat <span className="text-[#145C33] italic font-serif">Asupan</span></h2>
                        <p className="text-sm text-slate-500 mt-1">Pantau asupan nutrisi Anda untuk menjaga kesehatan.</p>
                    </div>

                    <div className="flex items-center justify-between bg-white rounded-2xl p-1.5 border border-[#E5EFE9] w-full md:w-auto shadow-sm">
                        <button onClick={() => changeDate(-1)} className="p-2.5 text-slate-400 hover:text-[#145C33] hover:bg-emerald-50 rounded-xl transition">
                            <ChevronLeft size={20} />
                        </button>
                        <div className="flex items-center gap-2 px-3 font-bold text-slate-700 text-sm">
                            <CalendarDays size={18} className="text-[#EA580C]"/>
                            <span>{formatDateIndo(selectedDate)}</span>
                            {selectedDate === today && <span className="text-[10px] bg-emerald-100 text-[#145C33] px-2 py-0.5 rounded-md ml-1">Hari ini</span>}
                        </div>
                        <button
                            onClick={() => changeDate(1)}
                            disabled={selectedDate === today}
                            className="p-2.5 text-slate-400 hover:text-[#145C33] hover:bg-emerald-50 rounded-xl transition disabled:opacity-30"
                        >
                            <ChevronRight size={20} />
                        </button>
                    </div>
                </div>

                {/* --- KARTU RINGKASAN GIZI --- */}
                <div className="bg-white rounded-[2rem] p-6 sm:p-8 shadow-sm border border-[#E5EFE9]">
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 sm:gap-6">

                        <div className="bg-slate-50 rounded-[1.5rem] p-4 sm:p-5 border border-slate-100 relative overflow-hidden group">
                            <div className="flex justify-between items-start mb-3 relative z-10">
                                <div className="p-2 sm:p-2.5 bg-blue-100 text-blue-600 rounded-xl"><Droplet size={20}/></div>
                                <span className="text-[10px] sm:text-xs font-black text-blue-600 bg-white px-2 py-1 rounded-lg border border-blue-100">{Math.round(pctNatrium)}%</span>
                            </div>
                            <p className="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest">Natrium</p>
                            <div className="flex items-end gap-1 mt-1 mb-3">
                                <span className="text-2xl sm:text-3xl font-extrabold text-slate-800">{totals.natrium}</span>
                                <span className="text-[10px] sm:text-xs font-semibold text-slate-400 mb-1">/ {BATAS_NATRIUM} mg</span>
                            </div>
                            <div className="w-full bg-slate-200 rounded-full h-1.5 overflow-hidden">
                                <div className={`h-full transition-all duration-700 ${pctNatrium > 100 ? 'bg-red-500' : 'bg-blue-500'}`} style={{ width: `${pctNatrium}%` }}></div>
                            </div>
                        </div>

                        <div className="bg-slate-50 rounded-[1.5rem] p-4 sm:p-5 border border-slate-100 relative overflow-hidden group">
                            <div className="flex justify-between items-start mb-3 relative z-10">
                                <div className="p-2 sm:p-2.5 bg-orange-100 text-[#EA580C] rounded-xl"><Flame size={20}/></div>
                                <span className="text-[10px] sm:text-xs font-black text-[#EA580C] bg-white px-2 py-1 rounded-lg border border-orange-100">{Math.round(pctKalori)}%</span>
                            </div>
                            <p className="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest">Kalori</p>
                            <div className="flex items-end gap-1 mt-1 mb-3">
                                <span className="text-2xl sm:text-3xl font-extrabold text-slate-800">{totals.kalori}</span>
                                <span className="text-[10px] sm:text-xs font-semibold text-slate-400 mb-1">/ {TARGET_KALORI} Kkal</span>
                            </div>
                            <div className="w-full bg-slate-200 rounded-full h-1.5 overflow-hidden">
                                <div className={`h-full transition-all duration-700 ${pctKalori > 100 ? 'bg-red-500' : 'bg-[#EA580C]'}`} style={{ width: `${pctKalori}%` }}></div>
                            </div>
                        </div>

                        <div className="bg-slate-50 rounded-[1.5rem] p-4 sm:p-5 border border-slate-100 relative overflow-hidden group">
                            <div className="flex justify-between items-start mb-3 relative z-10">
                                <div className="p-2 sm:p-2.5 bg-rose-100 text-rose-500 rounded-xl"><Beef size={20}/></div>
                                <span className="text-[10px] sm:text-xs font-black text-rose-500 bg-white px-2 py-1 rounded-lg border border-rose-100">{Math.round(pctProtein)}%</span>
                            </div>
                            <p className="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest">Protein</p>
                            <div className="flex items-end gap-1 mt-1 mb-3">
                                <span className="text-2xl sm:text-3xl font-extrabold text-slate-800">{totals.protein}</span>
                                <span className="text-[10px] sm:text-xs font-semibold text-slate-400 mb-1">/ {TARGET_PROTEIN} g</span>
                            </div>
                            <div className="w-full bg-slate-200 rounded-full h-1.5 overflow-hidden">
                                <div className={`h-full transition-all duration-700 ${pctProtein > 100 ? 'bg-red-500' : 'bg-rose-400'}`} style={{ width: `${pctProtein}%` }}></div>
                            </div>
                        </div>

                        <div className="bg-slate-50 rounded-[1.5rem] p-4 sm:p-5 border border-slate-100 relative overflow-hidden group">
                            <div className="flex justify-between items-start mb-3 relative z-10">
                                <div className="p-2 sm:p-2.5 bg-amber-100 text-amber-600 rounded-xl"><Wheat size={20}/></div>
                                <span className="text-[10px] sm:text-xs font-black text-amber-600 bg-white px-2 py-1 rounded-lg border border-amber-100">{Math.round(pctKarbo)}%</span>
                            </div>
                            <p className="text-[10px] sm:text-xs font-bold text-slate-400 uppercase tracking-widest">Karbo</p>
                            <div className="flex items-end gap-1 mt-1 mb-3">
                                <span className="text-2xl sm:text-3xl font-extrabold text-slate-800">{totals.karbo}</span>
                                <span className="text-[10px] sm:text-xs font-semibold text-slate-400 mb-1">/ {TARGET_KARBO} g</span>
                            </div>
                            <div className="w-full bg-slate-200 rounded-full h-1.5 overflow-hidden">
                                <div className={`h-full transition-all duration-700 ${pctKarbo > 100 ? 'bg-red-500' : 'bg-amber-400'}`} style={{ width: `${pctKarbo}%` }}></div>
                            </div>
                        </div>

                    </div>
                </div>

                {/* --- TABEL RIWAYAT MAKANAN --- */}
                <div className="bg-white rounded-[2rem] shadow-sm border border-[#E5EFE9] overflow-hidden mb-8">
                    <div className="px-6 py-5 sm:px-8 border-b border-[#E5EFE9] flex justify-between items-center bg-[#F8FBF8]">
                        <h3 className="font-extrabold text-slate-900 text-base sm:text-lg tracking-tight">Daftar Makanan</h3>
                        <button
                            onClick={openAddModal}
                            className="hidden md:flex text-white font-bold text-sm items-center gap-1 hover:bg-emerald-900 bg-[#145C33] px-4 py-2 rounded-xl transition shadow-md shadow-emerald-900/20"
                        >
                            <Plus size={16} /> Tambah Data
                        </button>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="w-full text-left whitespace-nowrap min-w-[700px]">
                            <thead>
                                <tr className="bg-[#F8FBF8] text-slate-400 text-[10px] uppercase tracking-widest border-b border-[#E5EFE9]">
                                    <th className="px-6 sm:px-8 py-4 font-black">Waktu</th>
                                    <th className="px-6 sm:px-8 py-4 font-black">Makanan / Porsi</th>
                                    <th className="px-6 sm:px-8 py-4 font-black text-right">Natrium</th>
                                    <th className="px-6 sm:px-8 py-4 font-black text-right">Kalori</th>
                                    <th className="px-6 sm:px-8 py-4 font-black text-right">Pro / Karbo</th>
                                    <th className="px-6 sm:px-8 py-4 font-black text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-[#E5EFE9]">
                                {allFoodsList.length === 0 ? (
                                    <tr>
                                        <td colSpan="6" className="px-6 py-16 text-center text-slate-400">
                                            <Utensils size={40} className="mx-auto mb-3 opacity-20" />
                                            <p className="font-medium text-sm">Belum ada makanan yang dicatat pada tanggal ini.</p>
                                        </td>
                                    </tr>
                                ) : (
                                    allFoodsList.map((food) => (
                                        <tr key={food.id} className="hover:bg-slate-50/50 transition-colors">
                                            <td className="px-6 sm:px-8 py-4">
                                                <span className={`px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-wider ${
                                                    food.waktu === 'pagi' ? 'bg-amber-50 text-amber-700 border border-amber-100' :
                                                    food.waktu === 'snack_pagi' || food.waktu === 'snack_sore' ? 'bg-lime-50 text-lime-700 border border-lime-100' :
                                                    food.waktu === 'siang' ? 'bg-orange-50 text-[#EA580C] border border-orange-100' :
                                                    'bg-indigo-50 text-indigo-700 border border-indigo-100'
                                                }`}>
                                                    {food.labelWaktu}
                                                </span>
                                            </td>
                                            <td className="px-6 sm:px-8 py-4">
                                                <p className="font-bold text-slate-800 text-sm">{food.nama_makanan}</p>
                                                <p className="text-xs font-semibold text-slate-500 mt-0.5">{food.porsi}</p>
                                            </td>
                                            <td className="px-6 sm:px-8 py-4 text-right">
                                                <p className="font-black text-blue-600 text-sm">{food.natrium} <span className="text-[10px] text-blue-400">mg</span></p>
                                            </td>
                                            <td className="px-6 sm:px-8 py-4 text-right">
                                                <p className="font-black text-[#EA580C] text-sm">{food.kalori} <span className="text-[10px] text-orange-400">Kkal</span></p>
                                            </td>
                                            <td className="px-6 sm:px-8 py-4 text-right">
                                                <p className="font-bold text-slate-700 text-xs">{food.protein}<span className="text-slate-400 font-medium">g P</span> / {food.karbo}<span className="text-slate-400 font-medium">g K</span></p>
                                            </td>
                                            <td className="px-6 sm:px-8 py-4 text-center">
                                                <button onClick={() => handleDeleteFood(food.id)} className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 border border-transparent hover:border-red-100 rounded-lg transition shadow-sm">
                                                    <Trash2 size={16} />
                                                </button>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>

            {/* --- MODAL INPUT MAKANAN --- */}
            {isModalOpen && (
                <div className="fixed inset-0 z-[100] flex items-end sm:items-center justify-center p-0 sm:p-6 bg-slate-900/60 backdrop-blur-sm transition-opacity">
                    <div className="bg-white w-full max-w-lg sm:rounded-[2rem] rounded-t-[2rem] shadow-2xl overflow-hidden animate-[slide-up_0.3s_ease-out] sm:animate-none flex flex-col max-h-[90vh]">

                        <div className="px-6 py-5 border-b border-[#E5EFE9] flex justify-between items-center bg-white shrink-0">
                            <h3 className="font-extrabold text-xl text-slate-900 tracking-tight">Catat Asupan</h3>
                            <button onClick={() => setIsModalOpen(false)} className="p-2 bg-slate-50 rounded-full text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition">
                                <X size={20} />
                            </button>
                        </div>

                        <form onSubmit={handleAddFood} className="p-6 space-y-6 overflow-y-auto flex-1 bg-slate-50/50">

                            {/* Waktu & Tanggal */}
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-bold text-slate-600 uppercase tracking-widest mb-2">Waktu Makan</label>
                                    <select
                                        value={data.waktu}
                                        onChange={e => setData('waktu', e.target.value)}
                                        className="w-full px-4 py-3 rounded-xl bg-white border border-slate-200 focus:ring-1 focus:ring-[#145C33] focus:border-[#145C33] font-bold text-slate-700 text-sm outline-none shadow-sm"
                                    >
                                        <option value="pagi">Sarapan</option>
                                        <option value="snack_pagi">Snack Pagi</option>
                                        <option value="siang">Makan Siang</option>
                                        <option value="snack_sore">Snack Sore</option>
                                        <option value="malam">Makan Malam</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-slate-600 uppercase tracking-widest mb-2">Tanggal</label>
                                    <input
                                        type="date"
                                        value={data.tanggal}
                                        onChange={e => setData('tanggal', e.target.value)}
                                        className="w-full px-4 py-3 rounded-xl bg-white border border-slate-200 focus:ring-1 focus:ring-[#145C33] focus:border-[#145C33] font-bold text-slate-700 text-sm outline-none shadow-sm"
                                        required
                                    />
                                </div>
                            </div>

                            {/* Pencarian Makanan */}
                            <div className="relative">
                                <label className="block text-xs font-bold text-slate-600 uppercase tracking-widest mb-2 flex justify-between">
                                    Nama Makanan / Minuman
                                    {isFromDatabase && <span className="text-[#145C33] flex items-center gap-1 text-[10px]"><ShieldCheck size={12}/> Data Tervalidasi</span>}
                                </label>
                                <div className="relative">
                                    <div className="absolute left-4 top-3.5 text-slate-400"><Utensils size={18}/></div>
                                    <input
                                        type="text"
                                        value={data.nama_makanan}
                                        onChange={e => {
                                            const value = e.target.value;
                                            setData('nama_makanan', value);
                                            setFoodQuery(value);
                                            setShowFoodSuggestions(true);
                                            // Jika user mengetik lagi, berarti mereka mengubah input menjadi manual
                                            if(isFromDatabase) setIsFromDatabase(false);
                                        }}
                                        onFocus={() => setShowFoodSuggestions(true)}
                                        onBlur={() => setTimeout(() => setShowFoodSuggestions(false), 200)}
                                        className={`w-full pl-12 pr-4 py-3 rounded-xl border focus:outline-none font-semibold text-sm shadow-sm transition-colors ${
                                            isFromDatabase ? 'bg-emerald-50 border-emerald-200 focus:ring-1 focus:ring-emerald-500 text-[#145C33]' : 'bg-white border-slate-200 focus:ring-1 focus:ring-[#145C33] text-slate-800'
                                        }`}
                                        placeholder="Ketik makanan (Misal: Nasi Goreng)..."
                                        required
                                    />
                                </div>

                                {/* Dropdown Saran Makanan */}
                                {showFoodSuggestions && foodQuery.length > 0 && (
                                    <div className="absolute z-50 mt-2 w-full max-h-60 overflow-y-auto rounded-[1.5rem] border border-slate-200 bg-white shadow-2xl">
                                        {filteredFoodOptions.length > 0 ? (
                                            filteredFoodOptions.map(option => (
                                                <button
                                                    type="button"
                                                    key={option.id}
                                                    onMouseDown={(e) => {
                                                        e.preventDefault();
                                                        setData({
                                                            ...data,
                                                            nama_makanan: option.nama_bahan,
                                                            kalori: option.energi || 0,
                                                            natrium: option.natrium || 0,
                                                            protein: option.protein || 0,
                                                            karbo: option.karbohidrat || 0,
                                                        });
                                                        setFoodQuery(option.nama_bahan);
                                                        setIsFromDatabase(true); // Kunci form makro
                                                        setShowFoodSuggestions(false);
                                                    }}
                                                    className="w-full text-left px-5 py-3.5 hover:bg-emerald-50 transition border-b border-slate-50 last:border-0"
                                                >
                                                    <p className="font-bold text-slate-800 mb-1">{option.nama_bahan}</p>
                                                    <div className="flex gap-4 text-xs font-semibold text-slate-500">
                                                        <span className="flex items-center gap-1"><Flame size={12} className="text-orange-500"/> {option.energi || 0} Kkal</span>
                                                        <span className="flex items-center gap-1"><Droplet size={12} className="text-blue-500"/> {option.natrium || 0} mg</span>
                                                    </div>
                                                </button>
                                            ))
                                        ) : (
                                            <div className="px-5 py-6 text-center">
                                                <p className="font-bold text-slate-700 text-sm mb-1">Makanan tidak ditemukan 🧐</p>
                                                <p className="text-xs text-slate-500 leading-relaxed">Teruskan mengetik nama makanan Anda dan isi kandungan gizinya secara manual di bawah ini.</p>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-slate-600 uppercase tracking-widest mb-2">Porsi / Takaran (Bisa Diedit)</label>
                                <input type="text" value={data.porsi} onChange={e => setData('porsi', e.target.value)} className="w-full px-4 py-3 rounded-xl bg-white border border-slate-200 focus:ring-1 focus:ring-[#145C33] focus:outline-none font-semibold text-sm text-slate-800 shadow-sm" placeholder="Cth: 1 Piring, 100gr, 1 Gelas" required />
                            </div>

                            {/* --- KOTAK INPUT GIZI (TERKUNCI JIKA DARI DATABASE) --- */}
                            <div className="bg-white p-5 rounded-2xl border border-[#E5EFE9] shadow-sm relative overflow-hidden">

                                <div className="flex justify-between items-center mb-4">
                                    <p className="text-xs font-extrabold text-slate-700 uppercase tracking-widest">Kandungan Gizi</p>
                                    {isFromDatabase ? (
                                        <span className="flex items-center gap-1 text-[10px] font-bold text-slate-400 bg-slate-100 px-2 py-1 rounded-md">
                                            <Lock size={12}/> Terkunci (Database)
                                        </span>
                                    ) : (
                                        <span className="flex items-center gap-1 text-[10px] font-bold text-amber-600 bg-amber-50 px-2 py-1 rounded-md border border-amber-100">
                                            <Unlock size={12}/> Mode Manual
                                        </span>
                                    )}
                                </div>

                                <div className="grid grid-cols-2 gap-4">
                                    {/* Natrium */}
                                    <div className="relative">
                                        <label className={`block text-[10px] font-bold mb-1 ${isFromDatabase ? 'text-slate-400' : 'text-blue-600'}`}>Natrium</label>
                                        <input type="number" readOnly={isFromDatabase} value={data.natrium} onChange={e => setData('natrium', e.target.value)}
                                            className={`w-full pl-3 pr-8 py-2.5 rounded-lg border text-sm focus:outline-none transition-colors ${isFromDatabase ? 'bg-slate-50 border-slate-200 text-slate-400 cursor-not-allowed' : 'bg-white border-blue-200 focus:ring-1 focus:ring-blue-500 text-blue-700 font-bold shadow-sm'}`} placeholder="0" required />
                                        <span className="absolute right-3 top-6 text-slate-400 font-medium text-xs">mg</span>
                                    </div>

                                    {/* Kalori */}
                                    <div className="relative">
                                        <label className={`block text-[10px] font-bold mb-1 ${isFromDatabase ? 'text-slate-400' : 'text-[#EA580C]'}`}>Kalori</label>
                                        <input type="number" readOnly={isFromDatabase} value={data.kalori} onChange={e => setData('kalori', e.target.value)}
                                            className={`w-full pl-3 pr-8 py-2.5 rounded-lg border text-sm focus:outline-none transition-colors ${isFromDatabase ? 'bg-slate-50 border-slate-200 text-slate-400 cursor-not-allowed' : 'bg-white border-orange-200 focus:ring-1 focus:ring-[#EA580C] text-[#EA580C] font-bold shadow-sm'}`} placeholder="0" required />
                                        <span className="absolute right-3 top-6 text-slate-400 font-medium text-xs">Kkal</span>
                                    </div>

                                    {/* Protein */}
                                    <div className="relative">
                                        <label className={`block text-[10px] font-bold mb-1 ${isFromDatabase ? 'text-slate-400' : 'text-rose-500'}`}>Protein</label>
                                        <input type="number" readOnly={isFromDatabase} value={data.protein} onChange={e => setData('protein', e.target.value)}
                                            className={`w-full pl-3 pr-8 py-2.5 rounded-lg border text-sm focus:outline-none transition-colors ${isFromDatabase ? 'bg-slate-50 border-slate-200 text-slate-400 cursor-not-allowed' : 'bg-white border-rose-200 focus:ring-1 focus:ring-rose-500 text-rose-600 font-bold shadow-sm'}`} placeholder="0" />
                                        <span className="absolute right-3 top-6 text-slate-400 font-medium text-xs">g</span>
                                    </div>

                                    {/* Karbohidrat */}
                                    <div className="relative">
                                        <label className={`block text-[10px] font-bold mb-1 ${isFromDatabase ? 'text-slate-400' : 'text-amber-600'}`}>Karbohidrat</label>
                                        <input type="number" readOnly={isFromDatabase} value={data.karbo} onChange={e => setData('karbo', e.target.value)}
                                            className={`w-full pl-3 pr-8 py-2.5 rounded-lg border text-sm focus:outline-none transition-colors ${isFromDatabase ? 'bg-slate-50 border-slate-200 text-slate-400 cursor-not-allowed' : 'bg-white border-amber-200 focus:ring-1 focus:ring-amber-500 text-amber-700 font-bold shadow-sm'}`} placeholder="0" />
                                        <span className="absolute right-3 top-6 text-slate-400 font-medium text-xs">g</span>
                                    </div>
                                </div>
                            </div>

                            <div className="pt-2 shrink-0">
                                <button type="submit" disabled={processing} className="w-full bg-[#145C33] text-white font-extrabold py-3.5 rounded-xl hover:bg-emerald-900 transition flex justify-center items-center gap-2 shadow-lg shadow-emerald-900/20 disabled:opacity-50">
                                    {processing ? 'Menyimpan...' : <><Plus size={20} /> Simpan Asupan</>}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
}
