"use client";

import * as React from "react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Modal } from "@/components/ui/modal";
import { formatDateID } from "@/lib/utils";
import {
  Calendar as CalendarIcon,
  ChevronLeft,
  ChevronRight,
  Plus,
  Clock,
  MapPin,
  Tag,
  Trash2,
} from "lucide-react";

interface CalendarEvent {
  id: string;
  title: string;
  description?: string | null;
  eventType: "EXAM" | "HOLIDAY" | "ASSIGNMENT" | "SCHOOL_EVENT" | "OSIS";
  startDate: string;
  endDate: string;
  isAllDay: boolean;
  location?: string | null;
}

interface AcademicCalendarViewProps {
  canManage?: boolean;
}

const EVENT_COLORS: Record<string, { bg: string; text: string; label: string; border: string }> = {
  EXAM: { bg: "bg-rose-50", text: "text-rose-700", border: "border-rose-200", label: "Ujian / Penilaian" },
  HOLIDAY: { bg: "bg-emerald-50", text: "text-emerald-700", border: "border-emerald-200", label: "Hari Libur" },
  ASSIGNMENT: { bg: "bg-purple-50", text: "text-purple-700", border: "border-purple-200", label: "Batas Tugas" },
  SCHOOL_EVENT: { bg: "bg-blue-50", text: "text-blue-700", border: "border-blue-200", label: "Kegiatan Sekolah" },
  OSIS: { bg: "bg-amber-50", text: "text-amber-700", border: "border-amber-200", label: "Kegiatan OSIS" },
};

export function AcademicCalendarView({ canManage = false }: AcademicCalendarViewProps) {
  const [events, setEvents] = React.useState<CalendarEvent[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [currentDate, setCurrentDate] = React.useState(new Date());
  const [typeFilter, setTypeFilter] = React.useState("ALL");

  // Create modal state
  const [createModalOpen, setCreateModalOpen] = React.useState(false);
  const [title, setTitle] = React.useState("");
  const [description, setDescription] = React.useState("");
  const [eventType, setEventType] = React.useState<string>("SCHOOL_EVENT");
  const [startDate, setStartDate] = React.useState("");
  const [endDate, setEndDate] = React.useState("");
  const [location, setLocation] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [formError, setFormError] = React.useState("");

  // Event detail modal state
  const [selectedEvent, setSelectedEvent] = React.useState<CalendarEvent | null>(null);

  const fetchEvents = React.useCallback(async () => {
    try {
      setLoading(true);
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      const res = await fetch(`/api/calendar?year=${year}&month=${month}&type=${typeFilter}`);
      const data = await res.json();
      if (data.success) {
        setEvents(data.data || []);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, [currentDate, typeFilter]);

  React.useEffect(() => {
    fetchEvents();
  }, [fetchEvents]);

  const handlePrevMonth = () => {
    setCurrentDate((prev) => new Date(prev.getFullYear(), prev.getMonth() - 1, 1));
  };

  const handleNextMonth = () => {
    setCurrentDate((prev) => new Date(prev.getFullYear(), prev.getMonth() + 1, 1));
  };

  const handleToday = () => {
    setCurrentDate(new Date());
  };

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!title.trim() || !startDate || !endDate) {
      setFormError("Judul kegiatan, tanggal mulai, dan selesai wajib diisi.");
      return;
    }

    try {
      setSubmitting(true);
      setFormError("");
      const res = await fetch("/api/calendar", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title,
          description,
          eventType,
          startDate,
          endDate,
          location,
          isAllDay: true,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setCreateModalOpen(false);
        setTitle("");
        setDescription("");
        setLocation("");
        fetchEvents();
      } else {
        setFormError(data.error || "Gagal membuat agenda.");
      }
    } catch (err) {
      setFormError("Terjadi gangguan jaringan.");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Hapus agenda ini dari kalender akademik?")) return;
    try {
      const res = await fetch(`/api/calendar/${id}`, { method: "DELETE" });
      const data = await res.json();
      if (data.success) {
        setSelectedEvent(null);
        fetchEvents();
      }
    } catch (err) {
      console.error(err);
    }
  };

  const monthName = currentDate.toLocaleDateString("id-ID", { month: "long", year: "numeric" });

  return (
    <div className="space-y-6">
      {/* Top Controls */}
      <Card>
        <CardContent className="p-4 flex flex-col sm:flex-row items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <h3 className="text-lg font-bold text-slate-800 capitalize min-w-[180px]">
              {monthName}
            </h3>
            <div className="flex items-center gap-1">
              <Button variant="outline" size="sm" onClick={handlePrevMonth} className="h-8 w-8 p-0">
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button variant="outline" size="sm" onClick={handleToday} className="h-8 px-2.5 text-xs">
                Bulan Ini
              </Button>
              <Button variant="outline" size="sm" onClick={handleNextMonth} className="h-8 w-8 p-0">
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="text-xs bg-white border border-slate-300 rounded-lg px-3 py-2 text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="ALL">Semua Kategori</option>
              <option value="EXAM">Ujian & PTS/PAS</option>
              <option value="HOLIDAY">Hari Libur</option>
              <option value="SCHOOL_EVENT">Kegiatan Sekolah</option>
              <option value="OSIS">Kegiatan OSIS</option>
            </select>

            {canManage && (
              <Button
                size="sm"
                onClick={() => {
                  setTitle("");
                  setDescription("");
                  setLocation("");
                  const todayStr = new Date().toISOString().split("T")[0];
                  setStartDate(todayStr);
                  setEndDate(todayStr);
                  setFormError("");
                  setCreateModalOpen(true);
                }}
                className="text-xs bg-blue-600 hover:bg-blue-700"
              >
                <Plus className="h-3.5 w-3.5 mr-1" />
                Tambah Agenda
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Events List */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {loading ? (
          <div className="col-span-full p-12 text-center text-slate-400 text-xs">
            Memuat agenda kalender...
          </div>
        ) : events.length === 0 ? (
          <div className="col-span-full p-12 text-center text-slate-500 bg-white rounded-xl border border-slate-200">
            <CalendarIcon className="h-10 w-10 text-slate-300 mx-auto mb-2" />
            <p className="font-semibold text-slate-700">Tidak ada agenda kegiatan</p>
            <p className="text-xs text-slate-400 mt-1">
              Tidak ada jadwal kegiatan atau hari libur tercatat pada bulan {monthName}.
            </p>
          </div>
        ) : (
          events.map((evt) => {
            const conf = EVENT_COLORS[evt.eventType] || EVENT_COLORS.SCHOOL_EVENT;
            const startFmt = formatDateID(evt.startDate);
            const endFmt = formatDateID(evt.endDate);
            const isSameDay = evt.startDate.split("T")[0] === evt.endDate.split("T")[0];

            return (
              <Card
                key={evt.id}
                onClick={() => setSelectedEvent(evt)}
                className={`cursor-pointer transition-all hover:shadow-md border-l-4 ${
                  evt.eventType === "EXAM"
                    ? "border-l-rose-500"
                    : evt.eventType === "HOLIDAY"
                    ? "border-l-emerald-500"
                    : evt.eventType === "OSIS"
                    ? "border-l-amber-500"
                    : "border-l-blue-500"
                }`}
              >
                <CardContent className="p-4 space-y-2.5">
                  <div className="flex items-center justify-between">
                    <Badge variant="outline" className={`text-[10px] ${conf.text} ${conf.bg} ${conf.border}`}>
                      {conf.label}
                    </Badge>
                  </div>

                  <h4 className="font-bold text-slate-900 text-sm leading-snug">
                    {evt.title}
                  </h4>

                  {evt.description && (
                    <p className="text-xs text-slate-600 line-clamp-2">
                      {evt.description}
                    </p>
                  )}

                  <div className="pt-2 border-t border-slate-100 space-y-1 text-[11px] text-slate-500">
                    <div className="flex items-center gap-1.5">
                      <Clock className="h-3.5 w-3.5 text-slate-400" />
                      <span>{isSameDay ? startFmt : `${startFmt} - ${endFmt}`}</span>
                    </div>
                    {evt.location && (
                      <div className="flex items-center gap-1.5">
                        <MapPin className="h-3.5 w-3.5 text-slate-400" />
                        <span className="truncate">{evt.location}</span>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>

      {/* Detail Modal */}
      {selectedEvent && (
        <Modal
          isOpen={true}
          onClose={() => setSelectedEvent(null)}
          title="Detail Agenda Akademik"
        >
          <div className="space-y-4 text-xs">
            <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-2">
              <Badge variant="outline" className="text-[10px]">
                {EVENT_COLORS[selectedEvent.eventType]?.label || selectedEvent.eventType}
              </Badge>
              <h3 className="text-base font-bold text-slate-900">{selectedEvent.title}</h3>
              {selectedEvent.description && (
                <p className="text-xs text-slate-700 whitespace-pre-line leading-relaxed">
                  {selectedEvent.description}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-700">
                <Clock className="h-4 w-4 text-slate-400" />
                <span className="font-medium">
                  {formatDateID(selectedEvent.startDate)} s/d {formatDateID(selectedEvent.endDate)}
                </span>
              </div>
              {selectedEvent.location && (
                <div className="flex items-center gap-2 text-slate-700">
                  <MapPin className="h-4 w-4 text-slate-400" />
                  <span>Lokasi: <strong>{selectedEvent.location}</strong></span>
                </div>
              )}
            </div>

            <div className="pt-4 flex items-center justify-between border-t border-slate-200">
              {canManage ? (
                <Button
                  variant="destructive"
                  size="sm"
                  onClick={() => handleDelete(selectedEvent.id)}
                  className="text-xs"
                >
                  <Trash2 className="h-3.5 w-3.5 mr-1" />
                  Hapus Agenda
                </Button>
              ) : <div />}

              <Button size="sm" variant="outline" onClick={() => setSelectedEvent(null)}>
                Tutup
              </Button>
            </div>
          </div>
        </Modal>
      )}

      {/* Create Event Modal */}
      {createModalOpen && (
        <Modal
          isOpen={true}
          onClose={() => setCreateModalOpen(false)}
          title="Tambah Agenda Kalender Akademik"
        >
          <form onSubmit={handleCreate} className="space-y-4 text-xs">
            {formError && (
              <div className="p-3 bg-rose-50 border border-rose-200 text-rose-700 rounded-lg">
                {formError}
              </div>
            )}

            <div>
              <label className="block font-semibold text-slate-700 mb-1">
                Nama Agenda / Kegiatan <span className="text-rose-500">*</span>
              </label>
              <Input
                placeholder="Contoh: Penilaian Tengah Semester (PTS) Ganjil"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                required
                className="text-xs"
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Kategori Agenda
                </label>
                <select
                  value={eventType}
                  onChange={(e) => setEventType(e.target.value)}
                  className="w-full bg-white border border-slate-300 rounded-lg px-3 py-2 text-xs text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="EXAM">Ujian & PTS/PAS</option>
                  <option value="HOLIDAY">Hari Libur Nasional / Semester</option>
                  <option value="SCHOOL_EVENT">Kegiatan Sekolah</option>
                  <option value="OSIS">Kegiatan OSIS / Ekstrakurikuler</option>
                </select>
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Lokasi / Ruang
                </label>
                <Input
                  placeholder="Contoh: Lingkungan Kampus SMAN 3 OKU"
                  value={location}
                  onChange={(e) => setLocation(e.target.value)}
                  className="text-xs"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Tanggal Mulai <span className="text-rose-500">*</span>
                </label>
                <Input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  required
                  className="text-xs"
                />
              </div>

              <div>
                <label className="block font-semibold text-slate-700 mb-1">
                  Tanggal Selesai <span className="text-rose-500">*</span>
                </label>
                <Input
                  type="date"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  required
                  className="text-xs"
                />
              </div>
            </div>

            <div>
              <label className="block font-semibold text-slate-700 mb-1">
                Keterangan Tambahan
              </label>
              <Textarea
                placeholder="Deskripsi kegiatan, tata tertib, atau informasi penting lainnya..."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                rows={3}
                className="text-xs"
              />
            </div>

            <div className="pt-2 flex justify-end gap-2">
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={() => setCreateModalOpen(false)}
              >
                Batal
              </Button>
              <Button
                type="submit"
                size="sm"
                disabled={submitting}
                className="bg-blue-600 hover:bg-blue-700"
              >
                {submitting ? "Menyimpan..." : "Simpan Agenda"}
              </Button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  );
}
