"use client";

import React, { useState, useMemo } from "react";
import Link from "next/link";
import {
  Calendar,
  Clock,
  MapPin,
  Users,
  Award,
  CheckCircle2,
  Download,
  Filter,
  Search,
  BookOpen,
  Printer,
  ChevronRight,
  Layers,
  Sparkles,
} from "lucide-react";
import { toast } from "sonner";

interface TimetableSlot {
  id: string;
  day: string;
  time: string;
  code: string;
  name: string;
  room: string;
  batch: string;
  semester: string;
  type: "PRACTICAL" | "THEORY";
  hours: number;
}

const fullWeeklyTimetable: Record<string, TimetableSlot[]> = {
  Monday: [
    {
      id: "tt-mon-1",
      day: "Monday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B1",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-mon-2",
      day: "Monday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM202",
      name: "Food & Beverage Service Theory",
      room: "Lecture Hall 101",
      batch: "Whole Cohort",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
    {
      id: "tt-mon-3",
      day: "Monday",
      time: "03:30 PM - 04:30 PM",
      code: "BHM101",
      name: "Culinary Foundation & Sanitation Theory",
      room: "Smart Room 204",
      batch: "Section A",
      semester: "Sem I",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Tuesday: [
    {
      id: "tt-tue-1",
      day: "Tuesday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B2",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-tue-2",
      day: "Tuesday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM301",
      name: "Advanced Culinary Techniques Theory",
      room: "Lecture Hall 102",
      batch: "Section A",
      semester: "Sem V",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Wednesday: [
    {
      id: "tt-wed-1",
      day: "Wednesday",
      time: "10:00 AM - 01:00 PM",
      code: "BHM203",
      name: "Bakery & Confectionery Practical",
      room: "Advanced Bakery Lab",
      batch: "Batch B1",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
    {
      id: "tt-wed-2",
      day: "Wednesday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM201",
      name: "Culinary Science & Nutrition Theory",
      room: "Smart Room 204",
      batch: "Whole Cohort",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
    {
      id: "tt-wed-3",
      day: "Wednesday",
      time: "03:30 PM - 04:30 PM",
      code: "FAC-DEV",
      name: "Department Faculty Coordination & Curriculum Sync",
      room: "Faculty Room F-04",
      batch: "Faculty Body",
      semester: "Academic Cell",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Thursday: [
    {
      id: "tt-thu-1",
      day: "Thursday",
      time: "09:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Food Production Operations Practical",
      room: "Basic Training Kitchen B",
      batch: "Batch B3",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 4.0,
    },
    {
      id: "tt-thu-2",
      day: "Thursday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM202",
      name: "Food & Beverage Service Theory",
      room: "Lecture Hall 101",
      batch: "Whole Cohort",
      semester: "Sem III",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Friday: [
    {
      id: "tt-fri-1",
      day: "Friday",
      time: "09:00 AM - 12:00 PM",
      code: "BHM203",
      name: "Bakery & Confectionery Practical",
      room: "Advanced Bakery Lab",
      batch: "Batch B2",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
    {
      id: "tt-fri-2",
      day: "Friday",
      time: "02:00 PM - 03:00 PM",
      code: "BHM301",
      name: "Menu Planning & Culinary Cost Control",
      room: "Lecture Hall 102",
      batch: "Whole Cohort",
      semester: "Sem V",
      type: "THEORY",
      hours: 1.0,
    },
  ],
  Saturday: [
    {
      id: "tt-sat-1",
      day: "Saturday",
      time: "10:00 AM - 01:00 PM",
      code: "BHM201",
      name: "Masterclass Workshop & Regional Indian Heritage Cuisine",
      room: "Amphitheatre Demo Kitchen",
      batch: "All Batches B1/B2/B3",
      semester: "Sem III",
      type: "PRACTICAL",
      hours: 3.0,
    },
  ],
};

export default function FacultyTimetablePage() {
  const [selectedDay, setSelectedDay] = useState("Monday");
  const [filterType, setFilterType] = useState<"ALL" | "PRACTICAL" | "THEORY">("ALL");
  const [searchQuery, setSearchQuery] = useState("");

  const daySlots = useMemo(() => {
    let slots = fullWeeklyTimetable[selectedDay] || [];
    if (filterType !== "ALL") {
      slots = slots.filter((s) => s.type === filterType);
    }
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      slots = slots.filter(
        (s) =>
          s.name.toLowerCase().includes(q) ||
          s.code.toLowerCase().includes(q) ||
          s.room.toLowerCase().includes(q)
      );
    }
    return slots;
  }, [selectedDay, filterType, searchQuery]);

  return (
    <div className="space-y-6 pb-14 font-sans bg-[#F8FAFC]">
      {/* 1. Header & Breadcrumb */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/faculty/dashboard" className="hover:text-[#1769E8] transition-colors">
            Faculty Console
          </Link>
          <span>&gt;</span>
          <span>Timetables &amp; Rosters</span>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Personalized Timetable</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2.5">
              <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
                Personalized Class Timetable
              </h1>
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-blue-50 text-[#1769E8] border border-blue-200">
                Autumn Term 2026–27
              </span>
            </div>
            <p className="text-[14px] text-[#64748B] mt-1 font-normal">
              Instructor: Chef Rajesh Sharma (FAC-101) • 18 Contact Hours / Week Allocated
            </p>
          </div>

          <div className="flex items-center gap-2.5">
            <button
              onClick={() => toast.success("Printing official faculty weekly timetable...")}
              className="px-3.5 py-2 bg-white border border-[#E2E8F0] hover:bg-slate-50 text-slate-700 rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-2xs transition-colors"
            >
              <Printer className="w-3.5 h-3.5 text-slate-600" />
              <span>Print Timetable</span>
            </button>
            <button
              onClick={() => toast.success("Exported Personalized Weekly Timetable PDF.")}
              className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold flex items-center gap-1.5 shadow-xs transition-colors"
            >
              <Download className="w-3.5 h-3.5" />
              <span>Export Timetable PDF</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Workload Metrics Quick Ribbon */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-3.5">
        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Total Weekly Load
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              18.0 Hours
            </div>
            <span className="text-[11px] text-emerald-600 font-semibold mt-0.5 block">
              100% NCHMCT Met
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center shrink-0 border border-blue-100">
            <Clock className="w-5 h-5" />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Kitchen Practicals
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              14.0 Hours
            </div>
            <span className="text-[11px] text-amber-600 font-semibold mt-0.5 block">
              4 Block Sessions
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-amber-50 text-amber-600 flex items-center justify-center shrink-0 border border-amber-100">
            <Award className="w-5 h-5" />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Theory Lectures
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              4.0 Hours
            </div>
            <span className="text-[11px] text-purple-600 font-semibold mt-0.5 block">
              4 Class Periods
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-purple-50 text-purple-600 flex items-center justify-center shrink-0 border border-purple-100">
            <BookOpen className="w-5 h-5" />
          </div>
        </div>

        <div className="bg-white rounded-xl border border-[#E5EAF0] p-4 shadow-xs flex items-center justify-between">
          <div>
            <span className="text-[11px] font-bold text-[#64748B] uppercase tracking-wider block">
              Training Venues
            </span>
            <div className="text-2xl font-bold font-heading text-[#071A4D] mt-0.5">
              4 Rooms
            </div>
            <span className="text-[11px] text-slate-500 font-semibold mt-0.5 block">
              Kitchens &amp; Lecture Halls
            </span>
          </div>
          <div className="w-10 h-10 rounded-xl bg-emerald-50 text-emerald-600 flex items-center justify-center shrink-0 border border-emerald-100">
            <MapPin className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* 3. Main Schedule Matrix Card */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        {/* Controls bar */}
        <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-white">
          <div className="relative flex-1 max-w-sm">
            <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
            <input
              type="text"
              placeholder="Search by subject, code, or room..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-9 pr-3 py-1.5 text-xs bg-slate-50 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#1769E8] focus:bg-white transition-colors"
            />
          </div>

          <div className="flex items-center gap-1.5 bg-slate-100 p-1 rounded-lg">
            <button
              onClick={() => setFilterType("ALL")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                filterType === "ALL" ? "bg-white text-[#071A4D] shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              All Types
            </button>
            <button
              onClick={() => setFilterType("PRACTICAL")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                filterType === "PRACTICAL" ? "bg-white text-amber-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Practicals (4h)
            </button>
            <button
              onClick={() => setFilterType("THEORY")}
              className={`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${
                filterType === "THEORY" ? "bg-white text-blue-700 shadow-2xs" : "text-slate-600 hover:text-slate-900"
              }`}
            >
              Theories (1h)
            </button>
          </div>
        </div>

        {/* Day Selector Navigation Pills */}
        <div className="p-3 bg-[#F8FAFC] border-b border-[#E5EAF0] flex items-center gap-2 overflow-x-auto">
          {Object.keys(fullWeeklyTimetable).map((day) => {
            const count = fullWeeklyTimetable[day].length;
            return (
              <button
                key={day}
                onClick={() => setSelectedDay(day)}
                className={`px-4 py-2 rounded-lg text-xs font-semibold transition-all flex items-center gap-2 ${
                  selectedDay === day
                    ? "bg-[#071A4D] text-white shadow-xs"
                    : "bg-white border border-[#E2E8F0] text-[#64748B] hover:text-[#071A4D] hover:bg-slate-50"
                }`}
              >
                <span>{day}</span>
                <span
                  className={`px-1.5 py-0.2 rounded-full text-[10px] ${
                    selectedDay === day ? "bg-white/20 text-white font-bold" : "bg-slate-100 text-slate-600"
                  }`}
                >
                  {count}
                </span>
              </button>
            );
          })}
        </div>

        {/* Timetable Session Slots Display */}
        <div className="p-5">
          <div className="space-y-3">
            {daySlots.length === 0 ? (
              <div className="p-10 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200 text-xs text-slate-500">
                No teaching sessions match your current filter on {selectedDay}.
              </div>
            ) : (
              daySlots.map((slot) => (
                <div
                  key={slot.id}
                  className="p-4 rounded-xl border border-[#E2E8F0] bg-white hover:border-[#1769E8]/40 hover:shadow-2xs transition-all flex flex-col md:flex-row md:items-center justify-between gap-4"
                >
                  <div className="flex items-start gap-4">
                    <div className="p-3 rounded-xl bg-blue-50 border border-blue-100 text-[#1769E8] shrink-0 text-center min-w-[100px]">
                      <span className="text-[10px] font-bold uppercase block text-[#1769E8]">
                        Time Slot
                      </span>
                      <span className="font-mono font-bold text-xs text-[#071A4D] block mt-0.5">
                        {slot.time.split(" - ")[0]}
                      </span>
                      <span className="text-[10px] text-slate-400 block">
                        to {slot.time.split(" - ")[1]}
                      </span>
                    </div>

                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF]">
                          {slot.code}
                        </span>
                        <span
                          className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${
                            slot.type === "PRACTICAL"
                              ? "bg-amber-50 text-amber-700 border-amber-200"
                              : "bg-blue-50 text-blue-700 border-blue-200"
                          }`}
                        >
                          {slot.type} • {slot.hours}h Contact
                        </span>
                        <span className="text-xs text-slate-500 font-medium">
                          {slot.batch} ({slot.semester})
                        </span>
                      </div>

                      <h4 className="font-heading font-bold text-sm text-[#071A4D]">
                        {slot.name}
                      </h4>

                      <div className="flex flex-wrap items-center gap-4 text-xs text-[#64748B]">
                        <span className="flex items-center gap-1 font-medium text-[#334155]">
                          <MapPin className="w-3.5 h-3.5 text-[#94A3B8]" />
                          Allocated Venue: <strong>{slot.room}</strong>
                        </span>
                        <span className="flex items-center gap-1">
                          <Clock className="w-3.5 h-3.5 text-[#94A3B8]" />
                          Scheduled Duration: {slot.time}
                        </span>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 pt-2 md:pt-0 border-t md:border-t-0 border-slate-100">
                    <Link
                      href="/faculty/rosters"
                      className="px-3.5 py-1.5 rounded-lg border border-[#E2E8F0] hover:bg-slate-50 text-[#334155] text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
                    >
                      <Users className="w-3.5 h-3.5 text-[#1769E8]" />
                      <span>Cohort Roster</span>
                    </Link>
                    <Link
                      href="/faculty/classes/today"
                      className="px-3.5 py-1.5 rounded-lg bg-[#1769E8] hover:bg-[#1255be] text-white text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
                    >
                      <CheckCircle2 className="w-3.5 h-3.5" />
                      <span>Take Attendance</span>
                    </Link>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
