import React, { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import { supabase } from '../services/supabaseClient';
import { DataSiswa } from '../types';
import { Save } from 'lucide-react';

export const Journal: React.FC = () => {
  const { user } = useAuth();
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    className: '',
    subject: '',
    timeSlot: '',
    topic: '',
    cleanliness: 'Bersih',
    kbmStatus: 'Tatap Muka'
  });
  const [students, setStudents] = useState<DataSiswa[]>([]);
  const [attendance, setAttendance] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [classes, setClasses] = useState<string[]>([]);

  useEffect(() => {
    fetchClasses();
  }, []);

  const fetchClasses = async () => {
    // Determine unique classes from data_siswa table
    const { data } = await supabase.from('data_siswa').select('kelas');
    if (data) {
      const unique = Array.from(new Set(data.map(d => d.kelas))).sort();
      setClasses(unique);
    }
  };

  const handleClassChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    const cls = e.target.value;
    setFormData({ ...formData, className: cls });
    if (cls) {
      setLoading(true);
      const { data } = await supabase
        .from('data_siswa')
        .select('*')
        .eq('kelas', cls)
        .order('nama');
      
      if (data) {
        setStudents(data);
        const initialAtt: Record<string, string> = {};
        data.forEach(s => initialAtt[s.nis] = 'H');
        setAttendance(initialAtt);
      }
      setLoading(false);
    }
  };

  const toggleAttendance = (nis: string, status: string) => {
    setAttendance(prev => ({
      ...prev,
      [nis]: prev[nis] === status ? 'H' : status
    }));
  };

  const submitJournal = async () => {
    setLoading(true);
    try {
      // 1. Insert ke Data_Jurnal (Header)
      const journalEntry = {
        nip_guru: user?.nip,
        nama_guru: user?.nama,
        kelas: formData.className,
        mapel: formData.subject,
        jam_ke: formData.timeSlot,
        materi: formData.topic,
        detail_absensi: attendance, // Simpan JSON untuk referensi cepat
        status_kebersihan: formData.cleanliness,
        status_kbm: formData.kbmStatus,
        tanggal: new Date().toISOString().split('T')[0]
      };

      const { data: journalData, error: journalError } = await supabase
        .from('data_jurnal')
        .insert([journalEntry])
        .select()
        .single();

      if (journalError) throw journalError;
      const idJurnal = journalData.id_jurnal;

      // 2. Insert ke Jurnal_Absensi (Detail Log) - Hanya yang tidak Hadir (atau semua jika perlu record lengkap)
      // Spreadsheet biasanya meminta detail yang tidak hadir, tapi DB relational lebih baik menyimpan log anomali saja untuk efisiensi
      // Namun untuk kelengkapan, mari kita simpan yang TIDAK HADIR saja.
      const logs = students
        .filter(s => attendance[s.nis] !== 'H')
        .map(s => ({
          tanggal: new Date().toISOString().split('T')[0],
          nis: s.nis,
          nama: s.nama,
          kelas: s.kelas,
          status: attendance[s.nis],
          jam_ke: formData.timeSlot,
          id_jurnal: idJurnal
        }));

      if (logs.length > 0) {
        const { error: logError } = await supabase.from('jurnal_absensi').insert(logs);
        if(logError) throw logError;
      }

      alert('Jurnal berhasil disimpan ke database!');
      setStep(1);
      setFormData({ className: '', subject: '', timeSlot: '', topic: '', cleanliness: 'Bersih', kbmStatus: 'Tatap Muka' });
    } catch (err: any) {
      alert('Gagal menyimpan: ' + err.message);
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
       <div className="flex justify-between items-center">
        <h1 className="text-2xl font-oswald text-white">INPUT JURNAL</h1>
        <span className="bg-slate-800 text-slate-400 text-xs px-2 py-1 rounded">Langkah {step}/2</span>
      </div>

      {step === 1 && (
        <div className="bg-card p-6 rounded-xl border border-gray-800 space-y-4">
           <div>
            <label className="block text-xs font-bold text-slate-400 uppercase mb-1">Kelas</label>
            <select 
              className="w-full bg-dark border border-gray-700 rounded-lg p-3 text-white"
              value={formData.className}
              onChange={handleClassChange}
            >
              <option value="">-- Pilih Kelas --</option>
              {classes.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
             <div>
                <label className="block text-xs font-bold text-slate-400 uppercase mb-1">Mapel</label>
                <input 
                  type="text" 
                  className="w-full bg-dark border border-gray-700 rounded-lg p-3 text-white"
                  value={formData.subject}
                  onChange={e => setFormData({...formData, subject: e.target.value})}
                  placeholder="Contoh: Matematika"
                />
             </div>
             <div>
                <label className="block text-xs font-bold text-slate-400 uppercase mb-1">Jam Ke</label>
                <input 
                  type="text" 
                  className="w-full bg-dark border border-gray-700 rounded-lg p-3 text-white"
                  value={formData.timeSlot}
                  onChange={e => setFormData({...formData, timeSlot: e.target.value})}
                  placeholder="1-2"
                />
             </div>
          </div>
          <div>
            <label className="block text-xs font-bold text-slate-400 uppercase mb-1">Materi</label>
            <textarea 
              className="w-full bg-dark border border-gray-700 rounded-lg p-3 text-white"
              rows={3}
              value={formData.topic}
              onChange={e => setFormData({...formData, topic: e.target.value})}
              placeholder="Topik pembelajaran hari ini..."
            ></textarea>
          </div>
          <div className="pt-4">
            <button 
              onClick={() => {
                if(!formData.className || !formData.topic) return alert("Lengkapi data");
                setStep(2);
              }}
              className="w-full bg-accent text-black font-bold font-oswald py-3 rounded-lg hover:bg-yellow-400"
            >
              LANJUT PRESENSI
            </button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div className="space-y-4">
          <div className="bg-card p-4 rounded-xl border border-gray-800">
             <h3 className="text-white font-oswald mb-4">DAFTAR SISWA {formData.className}</h3>
             
             {loading ? <div className="text-center py-8">Memuat siswa...</div> : (
               <div className="space-y-2">
                 {students.map((s, idx) => (
                   <div key={s.nis} className="flex items-center justify-between p-3 bg-dark rounded-lg border border-gray-800">
                      <div className="flex-1">
                        <span className="text-slate-500 font-mono text-xs mr-2">{idx+1}.</span>
                        <span className="text-white text-sm font-medium">{s.nama}</span>
                      </div>
                      <div className="flex gap-1">
                        {['S','I','A','D'].map(code => (
                          <button
                            key={code}
                            onClick={() => toggleAttendance(s.nis, code)}
                            className={`w-8 h-8 rounded text-xs font-bold transition-colors ${
                              attendance[s.nis] === code 
                                ? code === 'S' ? 'bg-blue-500 text-white' 
                                : code === 'I' ? 'bg-yellow-500 text-black'
                                : code === 'A' ? 'bg-red-500 text-white'
                                : 'bg-purple-500 text-white'
                                : 'bg-slate-800 text-slate-400 hover:bg-slate-700'
                            }`}
                          >
                            {code}
                          </button>
                        ))}
                      </div>
                   </div>
                 ))}
               </div>
             )}
          </div>

          <div className="grid grid-cols-2 gap-4">
             <button 
              onClick={() => setStep(1)}
              className="bg-dark border border-gray-700 text-white font-bold font-oswald py-3 rounded-lg"
            >
              KEMBALI
            </button>
            <button 
              onClick={submitJournal}
              disabled={loading}
              className="bg-green-600 text-white font-bold font-oswald py-3 rounded-lg flex items-center justify-center gap-2 hover:bg-green-500"
            >
              <Save size={18} />
              {loading ? 'MENYIMPAN...' : 'SIMPAN JURNAL'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
