"use client";

import * as React from "react";
import { Plus, Clock, MapPin, User, Calendar, Filter } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/modal";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";

interface SchedulesClientProps {
  initialSchedules: any[];
  classes: any[];
  teacherSubjects: any[];
}

const DAYS = [
  { id: 1, name: "Senin" },
  { id: 2, name: "Selasa" },
  { id: 3, name: "Rabu" },
  { id: 4, name: "Kamis" },
  { id: 5, name: "Jumat" },
  { id: 6, name: "Sabtu" },
];

export default function SchedulesClient({
  initialSchedules,
  classes,
  teacherSubjects,
}: SchedulesClientProps) {
  const [schedules, setSchedules] = React.useState(initialSchedules);
  const [selectedClassId, setSelectedClassId] = React.useState(classes[0]?.id || "ALL");

  // Modal State
  const [modalOpen, setModalOpen] = React.useState(false);
  const [teacherSubjectId, setTeacherSubjectId] = React.useState(teacherSubjects[0]?.id || "");
  const [dayOfWeek, setDayOfWeek] = React.useState("1");
  const [startTime, setStartTime] = React.useState("07:30");
  const [endTime, setEndTime] = React.useState("09:00");
  const [room, setRoom] = React.useState("Ruang Kelas");
  const [isLoading, setIsLoading] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState("");

  const filteredSchedules = schedules.filter((s) => {
    if (selectedClassId === "ALL") return true;
    return s.teacherSubject.classId === selectedClassId;
  });

  const handleCreateSchedule = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setErrorMsg("");

    try {
      const res = await fetch("/api/academic/schedules", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          teacherSubjectId,
          dayOfWeek,
          startTime,
          endTime,
          room,
        }),
      });

      const data = await res.json();
      if (!res.ok || !data.success) {
        setErrorMsg(data.error || "Gagal membuat jadwal.");
        setIsLoading(false);
        return;
      }

      setModalOpen(false);
      window.location.reload();
    } catch (err) {
      setErrorMsg("Terjadi gangguan jaringan.");
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* Filters and Add button */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex items-center gap-2 w-full sm:w-auto">
          <Filter className="h-4 w-4 text-slate-400" />
          <Select
            value={selectedClassId}
            onChange={(e) => setSelectedClassId(e.target.value)}
            className="w-full sm:w-60"
          >
            <option value="ALL">Semua Rombel Kelas</option>
            {classes.map((c) => (
              <option key={c.id} value={c.id}>
                Kelas {c.name}
              </option>
            ))}
          </Select>
        </div>

        <Button
          size="sm"
          onClick={() => setModalOpen(true)}
          className="w-full sm:w-auto font-bold"
        >
          <Plus className="mr-1.5 h-4 w-4" />
          Tambah Slot Jadwal
        </Button>
      </div>

      {/* WEEKLY GRID: Senin - Sabtu */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        {DAYS.map((day) => {
          const daySlots = filteredSchedules.filter((s) => s.dayOfWeek === day.id);
          return (
            <div
              key={day.id}
              className="flex flex-col rounded-2xl border border-slate-200 bg-white p-3.5 shadow-sm space-y-3 min-h-[300px]"
            >
              <div className="flex items-center justify-between border-b border-slate-100 pb-2">
                <span className="font-extrabold text-xs text-slate-800 uppercase tracking-wider">
                  {day.name}
                </span>
                <span className="text-[10px] font-bold text-slate-400">
                  {daySlots.length} Jam
                </span>
              </div>

              <div className="space-y-2 flex-1">
                {daySlots.length === 0 ? (
                  <p className="text-center text-[11px] text-slate-400 py-12">
                    Kosong
                  </p>
                ) : (
                  daySlots.map((slot) => (
                    <div
                      key={slot.id}
                      className="p-3 rounded-xl border border-blue-100 bg-blue-50/60 hover:bg-blue-50 transition-all space-y-1"
                    >
                      <div className="flex items-center justify-between">
                        <span className="text-[11px] font-black text-blue-700 font-mono">
                          {slot.startTime} - {slot.endTime}
                        </span>
                        <Badge variant="primary" className="text-[9px] px-1.5 py-0">
                          {slot.teacherSubject.class.name}
                        </Badge>
                      </div>

                      <h5 className="text-xs font-bold text-slate-900 leading-snug">
                        {slot.teacherSubject.subject.name}
                      </h5>

                      <p className="text-[10px] text-slate-500 truncate flex items-center gap-1">
                        <User className="h-3 w-3" />
                        {slot.teacherSubject.teacher.fullName}
                      </p>

                      {slot.room && (
                        <p className="text-[10px] text-slate-400 flex items-center gap-1">
                          <MapPin className="h-3 w-3" />
                          {slot.room}
                        </p>
                      )}
                    </div>
                  ))
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* Modal Tambah Slot Jadwal */}
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title="Tambah Slot Jadwal Pelajaran"
        description="Tentukan mata pelajaran, kelas, hari, dan rentang jam pelajaran."
      >
        <form onSubmit={handleCreateSchedule} className="space-y-4">
          {errorMsg && (
            <div className="p-3 rounded-lg bg-rose-50 border border-rose-200 text-rose-700 text-xs">
              {errorMsg}
            </div>
          )}

          <Select
            label="Mata Pelajaran, Guru & Kelas"
            value={teacherSubjectId}
            onChange={(e) => setTeacherSubjectId(e.target.value)}
          >
            {teacherSubjects.map((ts) => (
              <option key={ts.id} value={ts.id}>
                {ts.subject.name} - Kelas {ts.class.name} ({ts.teacher.fullName})
              </option>
            ))}
          </Select>

          <Select
            label="Hari"
            value={dayOfWeek}
            onChange={(e) => setDayOfWeek(e.target.value)}
          >
            {DAYS.map((d) => (
              <option key={d.id} value={d.id}>
                {d.name}
              </option>
            ))}
          </Select>

          <div className="grid grid-cols-2 gap-3">
            <Input
              label="Jam Mulai"
              type="time"
              value={startTime}
              onChange={(e) => setStartTime(e.target.value)}
              required
            />
            <Input
              label="Jam Selesai"
              type="time"
              value={endTime}
              onChange={(e) => setEndTime(e.target.value)}
              required
            />
          </div>

          <Input
            label="Ruang / Laboratorium"
            placeholder="Contoh: Ruang X.1 atau Lab Komputer 1"
            value={room}
            onChange={(e) => setRoom(e.target.value)}
          />

          <div className="flex justify-end gap-2.5 pt-4 border-t border-slate-100">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => setModalOpen(false)}
            >
              Batal
            </Button>
            <Button type="submit" size="sm" isLoading={isLoading}>
              Simpan Jadwal
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
