"use client";

import { useEffect, useState } from "react";
import axios from "axios";
import { CalendarDays, Plus, Trash2, Clock, MapPin, LayoutList, Calendar, Edit, X, Save } from "lucide-react";

export default function SchedulesPage() {
  const [schedules, setSchedules] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [viewMode, setViewMode] = useState<"table" | "calendar">("table");

  // STATE UNTUK MODAL FORM (TAMBAH & EDIT)
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [formData, setFormData] = useState({
    schedule_id: null as number | null,
    kode_mk: "",
    nama_mk: "",
    room_id: 1, // Default Kelas D101
    hari: "Senin",
    jam_mulai: "",
    jam_selesai: "",
    jumlah_sks: 2,
  });

  const hariUrutan = ["Senin", "Selasa", "Rabu", "Kamis", "Jumat"];
  const listJam = ["07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00"];

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

  const fetchSchedules = async () => {
    try {
      const token = localStorage.getItem("token");
      const res = await axios.get("http://172.17.172.17:8080/api/schedules", {
        headers: { Authorization: `Bearer ${token}` }
      });
      setSchedules(res.data.data || []);
    } catch (err: any) {
      console.error("Gagal ambil jadwal:", err);
      setSchedules([]);
    } finally {
      setLoading(false);
    }
  };

  // =========================================================================
  // FUNGSI CRUD (TAMBAH, EDIT, HAPUS)
  // =========================================================================
  
  // 1. Buka Modal untuk Tambah Baru
  const handleAddClick = () => {
    setFormData({
      schedule_id: null,
      kode_mk: "",
      nama_mk: "",
      room_id: 1,
      hari: "Senin",
      jam_mulai: "07:00",
      jam_selesai: "08:40",
      jumlah_sks: 2,
    });
    setIsModalOpen(true);
  };

  // 2. Buka Modal untuk Edit Data Lama
  const handleEditClick = (sched: any) => {
    setFormData({
      schedule_id: sched.schedule_id,
      kode_mk: sched.kode_mk,
      nama_mk: sched.nama_mk,
      room_id: sched.room_id,
      hari: sched.hari,
      jam_mulai: sched.jam_mulai.substring(0, 5), // Potong detik jika ada (07:00:00 -> 07:00)
      jam_selesai: sched.jam_selesai.substring(0, 5),
      jumlah_sks: sched.jumlah_sks || 2,
    });
    setIsModalOpen(true);
  };

  // 3. Simpan Data (Create atau Update ke Backend)
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    try {
      const token = localStorage.getItem("token");
      const headers = { Authorization: `Bearer ${token}` };

      // Format ulang jam agar aman (tambahkan detik 00)
      const payload = {
        ...formData,
        jam_mulai: formData.jam_mulai.length === 5 ? `${formData.jam_mulai}:00` : formData.jam_mulai,
        jam_selesai: formData.jam_selesai.length === 5 ? `${formData.jam_selesai}:00` : formData.jam_selesai,
        jumlah_sks: Number(formData.jumlah_sks)
      };

      if (formData.schedule_id) {
        // UPDATE (PUT)
        await axios.put(`http://172.17.172.17:8080/api/schedules/${formData.schedule_id}`, payload, { headers });
        alert("Jadwal berhasil diperbarui!");
      } else {
        // CREATE BARU (POST)
        await axios.post("http://172.17.172.17:8080/api/schedules", payload, { headers });
        alert("Jadwal baru berhasil ditambahkan!");
      }
      
      setIsModalOpen(false);
      fetchSchedules(); // Refresh data di tabel
    } catch (err: any) {
      console.error("Gagal menyimpan jadwal:", err);
      alert("Gagal menyimpan data: " + (err.response?.data?.error || err.message));
    } finally {
      setIsSaving(false);
    }
  };

  // 4. Hapus Data (Delete)
  const handleDelete = async (id: number, namaMK: string) => {
    if (!window.confirm(`Apakah Anda yakin ingin menghapus jadwal mata kuliah ${namaMK}?`)) return;
    
    try {
      const token = localStorage.getItem("token");
      await axios.delete(`http://172.17.172.17:8080/api/schedules/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      alert("Jadwal berhasil dihapus!");
      fetchSchedules();
    } catch (err: any) {
      alert("Gagal menghapus jadwal.");
    }
  };

  const getMatkulDiSlot = (hari: string, jam: string) => {
    return schedules.find((s) => {
      if (s.hari !== hari) return false;
      const jamMulai = s.jam_mulai.substring(0, 5);
      const jamSelesai = s.jam_selesai.substring(0, 5);
      return jam >= jamMulai && jam < jamSelesai;
    });
  };

  if (loading) return <div className="p-8 text-gray-500 font-medium">Memuat Jadwal Kuliah...</div>;

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      
      {/* Header Halaman */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
        <div className="flex items-center gap-3">
          <div className="bg-blue-100 p-3 rounded-lg text-blue-600">
            <CalendarDays size={28} />
          </div>
          <div>
            <h2 className="text-2xl font-bold text-gray-800">Edit Jadwal</h2>
            <p className="text-gray-500 text-sm mt-1">Pantau dan Kelola Jadwal Ruangan.</p>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          {/* Tombol Tambah Jadwal */}
          <button 
            onClick={handleAddClick}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-bold hover:bg-blue-700 transition-all shadow-sm"
          >
            <Plus size={16} /> Tambah Jadwal
          </button>

          {/* Toggle View Mode */}
          <div className="bg-gray-100 p-1 rounded-lg flex items-center border border-gray-200">
            <button 
              onClick={() => setViewMode("table")}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${viewMode === "table" ? "bg-white text-blue-600 shadow-sm" : "text-gray-600 hover:text-gray-900"}`}
            >
              <LayoutList size={14} /> Mode Tabel
            </button>
            <button 
              onClick={() => setViewMode("calendar")}
              className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-bold transition-all ${viewMode === "calendar" ? "bg-white text-blue-600 shadow-sm" : "text-gray-600 hover:text-gray-900"}`}
            >
              <Calendar size={14} /> Mode Kalender
            </button>
          </div>
        </div>
      </div>

      {/* ==================================== MODE TABEL ==================================== */}
      {viewMode === "table" && (
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead className="bg-gray-50 text-gray-500 text-xs font-bold uppercase border-b border-gray-100">
                <tr>
                  <th className="p-4">Kode MK</th>
                  <th className="p-4">Mata Kuliah</th>
                  <th className="p-4">Ruangan</th>
                  <th className="p-4">Hari & Waktu</th>
                  <th className="p-4">SKS</th>
                  <th className="p-4 text-center">Aksi</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {schedules.length > 0 ? (
                  schedules.map((sched) => (
                    <tr key={sched.schedule_id} className="hover:bg-blue-50/30 transition-colors">
                      <td className="p-4 font-bold text-blue-700 text-sm">{sched.kode_mk}</td>
                      <td className="p-4 text-sm font-semibold text-gray-800">{sched.nama_mk}</td>
                      <td className="p-4 text-sm font-bold text-gray-600 flex items-center gap-1.5 mt-2">
                        <MapPin size={14} className="text-blue-500" /> Kelas D101
                      </td>
                      <td className="p-4 text-sm text-gray-600">
                        <div className="font-bold text-gray-700">{sched.hari}</div>
                        <div className="flex items-center gap-1.5 font-medium text-xs mt-0.5">
                          <Clock size={12} className="text-gray-400" />
                          {sched.jam_mulai.substring(0, 5)} - {sched.jam_selesai.substring(0, 5)}
                        </div>
                      </td>
                      <td className="p-4 text-sm font-bold text-gray-600 text-center">
                        <span className="bg-gray-100 px-2 py-1 rounded-md border">{sched.jumlah_sks}</span>
                      </td>
                      <td className="p-4">
                        <div className="flex items-center justify-center gap-2">
                          <button 
                            onClick={() => handleEditClick(sched)}
                            className="p-2 bg-yellow-50 text-yellow-600 rounded-lg hover:bg-yellow-100 transition-colors"
                            title="Edit Jadwal"
                          >
                            <Edit size={16} />
                          </button>
                          <button 
                            onClick={() => handleDelete(sched.schedule_id, sched.nama_mk)}
                            className="p-2 bg-red-50 text-red-500 rounded-lg hover:bg-red-100 transition-colors"
                            title="Hapus Jadwal"
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={6} className="p-10 text-center text-gray-400 text-sm">Belum ada jadwal kuliah terdaftar.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* ==================================== MODE KALENDER ==================================== */}
      {viewMode === "calendar" && (
        <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="grid grid-cols-6 gap-2 border-b border-gray-100 pb-3 text-center font-bold text-sm text-gray-500">
            <div>Waktu</div>
            {hariUrutan.map((h) => <div key={h} className="text-gray-700">{h}</div>)}
          </div>

          <div className="divide-y divide-gray-100">
            {listJam.map((jam) => (
              <div key={jam} className="grid grid-cols-6 gap-2 py-3 items-center min-h-17.5">
                <div className="text-xs font-bold text-gray-400 text-center flex items-center justify-center gap-1">
                  <Clock size={12} /> {jam}
                </div>
                
                {hariUrutan.map((hari) => {
                  const mtk = getMatkulDiSlot(hari, jam);
                  return (
                    <div key={hari} className="h-full">
                      {mtk ? (
                        <div 
                          onClick={() => handleEditClick(mtk)} 
                          className="bg-blue-50 border-l-4 border-blue-600 p-2 rounded text-left shadow-xs h-full flex flex-col justify-between cursor-pointer hover:bg-blue-100 transition-colors"
                          title="Klik untuk Edit"
                        >
                          <span className="text-xs font-bold text-blue-800 block truncate">{mtk.nama_mk}</span>
                          <span className="text-[10px] font-semibold text-blue-500">{mtk.kode_mk}</span>
                        </div>
                      ) : (
                        <div className="border border-dashed border-gray-100 h-full rounded flex items-center justify-center text-[10px] text-gray-300">
                          Kosong
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ==================================== MODAL FORM CRUD ==================================== */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
          <div className="bg-white rounded-2xl w-full max-w-lg shadow-xl overflow-hidden">
            <div className="flex justify-between items-center p-5 border-b border-gray-100 bg-gray-50/50">
              <h3 className="font-bold text-lg text-gray-800">
                {formData.schedule_id ? "Edit Jadwal Kuliah" : "Tambah Jadwal Kuliah Baru"}
              </h3>
              <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500">
                <X size={20} />
              </button>
            </div>
            
            <form onSubmit={handleSubmit} className="p-6 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-600 mb-1">Kode MK</label>
                  <input type="text" required value={formData.kode_mk} onChange={(e) => setFormData({...formData, kode_mk: e.target.value.toUpperCase()})}
                    className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none uppercase" 
                    placeholder="Contoh: EE153" 
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-600 mb-1">Jumlah SKS</label>
                  <input type="number" min="1" max="6" required value={formData.jumlah_sks} onChange={(e) => setFormData({...formData, jumlah_sks: Number(e.target.value)})}
                    className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold text-gray-600 mb-1">Nama Mata Kuliah</label>
                <input type="text" required value={formData.nama_mk} onChange={(e) => setFormData({...formData, nama_mk: e.target.value})}
                  className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  placeholder="Contoh: Elektronika dan Sistem Digital" 
                />
              </div>

              <div>
                <label className="block text-xs font-bold text-gray-600 mb-1">Hari Pelaksanaan</label>
                <select value={formData.hari} onChange={(e) => setFormData({...formData, hari: e.target.value})}
                  className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none bg-white">
                  {hariUrutan.map(h => <option key={h} value={h}>{h}</option>)}
                  <option value="Sabtu">Sabtu</option>
                </select>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-600 mb-1">Jam Mulai</label>
                  <input type="time" required value={formData.jam_mulai} onChange={(e) => setFormData({...formData, jam_mulai: e.target.value})}
                    className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-600 mb-1">Jam Selesai</label>
                  <input type="time" required value={formData.jam_selesai} onChange={(e) => setFormData({...formData, jam_selesai: e.target.value})}
                    className="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
              </div>

              <div className="pt-4 flex gap-3">
                <button type="button" onClick={() => setIsModalOpen(false)} className="flex-1 py-2.5 rounded-lg text-sm font-bold text-gray-600 bg-gray-100 hover:bg-gray-200 transition-colors">
                  Batal
                </button>
                <button type="submit" disabled={isSaving} className={`flex-1 py-2.5 rounded-lg text-sm font-bold text-white transition-colors flex items-center justify-center gap-2 ${isSaving ? 'bg-blue-400' : 'bg-blue-600 hover:bg-blue-700'}`}>
                  <Save size={16} /> {isSaving ? "Menyimpan..." : "Simpan Jadwal"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  );
}