"use client";

import { useEffect, useState } from "react";
import axios from "axios";
import { CalendarDays, Plus, Trash2, Clock, MapPin, LayoutList, Calendar } 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 pindah mode

  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);
    }
  };

  // Helper untuk mengecek apakah ada matkul di hari dan jam tertentu (Untuk Mode Kalender)
  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">Jadwal Kuliah Statis</h2>
            <p className="text-gray-500 text-sm mt-1">Pantau kepadatan ruang kelas D101 dan kelola jadwal otomatis.</p>
          </div>
        </div>
        
        <div className="flex items-center gap-3">
          {/* 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>

          <button className="flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg text-sm font-bold shadow-sm hover:bg-blue-700 transition-colors">
            <Plus size={18} /> Tambah Jadwal
          </button>
        </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</th>
                  <th className="p-4">Waktu</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-gray-800 text-sm">{sched.kode_mk}</td>
                      <td className="p-4 text-sm font-semibold text-gray-600">{sched.nama_mk}</td>
                      <td className="p-4 text-sm font-bold text-blue-600 flex items-center gap-1.5 mt-2">
                        <MapPin size={14} /> Kelas D101
                      </td>
                      <td className="p-4 text-sm font-bold text-gray-700">
                        <span className="bg-gray-100 px-2 py-1 rounded-md">{sched.hari}</span>
                      </td>
                      <td className="p-4 text-sm text-gray-600">
                        <div className="flex items-center gap-1.5 font-medium">
                          <Clock size={14} className="text-gray-400" />
                          {sched.jam_mulai.substring(0, 5)} - {sched.jam_selesai.substring(0, 5)}
                        </div>
                      </td>
                      <td className="p-4 text-center">
                        <button className="p-2 bg-red-50 text-red-500 rounded-lg hover:bg-red-100 transition-colors">
                          <Trash2 size={16} />
                        </button>
                      </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 className="bg-blue-50 border-l-4 border-blue-600 p-2 rounded text-left shadow-xs h-full flex flex-col justify-between">
                          <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>
      )}
      
    </div>
  );
}