'use client';

import { Calendar, Plus } from 'lucide-react';
import { useCallback, useEffect, useState, type FormEvent } from 'react';
import { AdminShell } from '@/components/admin-shell';
import {
  ConfirmDialog,
  EmptyState,
  ErrorBanner,
  LoadingSkeleton,
  PageHeader,
  StatusBadge,
} from '@/components/ui/admin-ui';
import {
  proxyFetch,
  type AcademicOverviewPayload,
  type RoutineEntryItem,
  type RoutineExceptionItem,
  type TeacherListItem,
} from '@/lib/proxy-client';

const WEEKDAYS = ['SATURDAY', 'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY'] as const;

export default function RoutinePage() {
  const [overview, setOverview] = useState<AcademicOverviewPayload | null>(null);
  const [teachers, setTeachers] = useState<TeacherListItem[]>([]);
  const [entries, setEntries] = useState<RoutineEntryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [banner, setBanner] = useState<{ kind: 'error' | 'success'; text: string } | null>(null);

  const [programId, setProgramId] = useState('');
  const [departmentId, setDepartmentId] = useState('');
  const [sessionId, setSessionId] = useState('');
  const [termId, setTermId] = useState('');
  const [batchId, setBatchId] = useState('');
  const [sectionId, setSectionId] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  const [offeringId, setOfferingId] = useState('');
  const [teacherId, setTeacherId] = useState('');
  const [weekday, setWeekday] = useState<string>('SUNDAY');
  const [startTime, setStartTime] = useState('09:00');
  const [endTime, setEndTime] = useState('10:00');
  const [room, setRoom] = useState('');

  const [pendingAction, setPendingAction] = useState<{
    id: string;
    kind: 'publish' | 'archive';
    label: string;
  } | null>(null);
  const [busy, setBusy] = useState(false);

  const [exceptions, setExceptions] = useState<RoutineExceptionItem[]>([]);
  const [exEntryId, setExEntryId] = useState('');
  const [exDate, setExDate] = useState('');
  const [exType, setExType] = useState<'CANCELLED' | 'RESCHEDULED'>('CANCELLED');
  const [exReason, setExReason] = useState('');
  const [exStartTime, setExStartTime] = useState('11:00');
  const [exEndTime, setExEndTime] = useState('12:00');
  const [exRoom, setExRoom] = useState('');

  const loadRoutine = useCallback(async (secId: string, tId: string, st: string) => {
    const params = new URLSearchParams();
    if (secId) params.set('sectionId', secId);
    if (tId) params.set('termId', tId);
    if (st) params.set('status', st);
    const res = await proxyFetch<RoutineEntryItem[]>(`admin/routine?${params.toString()}`);
    if (res.success) {
      setEntries(res.data);
    } else {
      setBanner({ kind: 'error', text: res.error.message });
    }
  }, []);

  useEffect(() => {
    let active = true;
    void Promise.all([
      proxyFetch<AcademicOverviewPayload>('admin/academics/overview'),
      proxyFetch<TeacherListItem[]>('admin/teachers'),
      proxyFetch<RoutineEntryItem[]>('admin/routine'),
      proxyFetch<RoutineExceptionItem[]>('admin/routine/exceptions'),
    ]).then(([aRes, tRes, rRes, exRes]) => {
      if (!active) return;
      if (aRes.success) {
        setOverview(aRes.data);
        setProgramId(aRes.data.programs[0]?.id ?? '');
        setDepartmentId(aRes.data.departments[0]?.id ?? '');
        setSessionId(aRes.data.sessions[0]?.id ?? '');
        setTermId(aRes.data.terms[0]?.id ?? '');
        setBatchId(aRes.data.batches[0]?.id ?? '');
        setSectionId(aRes.data.sections[0]?.id ?? '');
        setOfferingId(aRes.data.offerings[0]?.id ?? '');
      } else {
        setBanner({ kind: 'error', text: aRes.error.message });
      }
      if (tRes.success) {
        setTeachers(tRes.data);
        setTeacherId(tRes.data[0]?.id ?? '');
      }
      if (rRes.success) {
        setEntries(rRes.data);
        setExEntryId(rRes.data[0]?.id ?? '');
      }
      if (exRes.success) {
        setExceptions(exRes.data);
      }
      setLoading(false);
    });
    return () => {
      active = false;
    };
  }, []);

  async function reloadExceptions() {
    const res = await proxyFetch<RoutineExceptionItem[]>('admin/routine/exceptions');
    if (res.success) {
      setExceptions(res.data);
    }
  }

  async function handleCreateException(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!exEntryId || !exDate) return;
    setBanner(null);
    setBusy(true);
    const res = await proxyFetch<RoutineExceptionItem>(`admin/routine/${exEntryId}/exceptions`, {
      method: 'POST',
      body: JSON.stringify({
        exceptionDate: exDate,
        type: exType,
        reason: exReason.trim() || undefined,
        ...(exType === 'RESCHEDULED'
          ? {
              overrideStartTime: exStartTime,
              overrideEndTime: exEndTime,
              overrideRoom: exRoom.trim() || undefined,
            }
          : {}),
      }),
    });
    setBusy(false);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setExReason('');
    setExRoom('');
    setBanner({ kind: 'success', text: `Schedule exception (${exType}) created.` });
    await reloadExceptions();
  }

  async function handleDeleteException(exceptionId: string) {
    setBanner(null);
    setBusy(true);
    const res = await proxyFetch<{ deleted: boolean }>(`admin/routine/exceptions/${exceptionId}`, {
      method: 'DELETE',
    });
    setBusy(false);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setBanner({ kind: 'success', text: 'Schedule exception removed.' });
    await reloadExceptions();
  }

  async function handleCreate(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setBanner(null);
    setBusy(true);
    const res = await proxyFetch<RoutineEntryItem>('admin/routine', {
      method: 'POST',
      body: JSON.stringify({
        subjectOfferingId: offeringId,
        teacherProfileId: teacherId,
        weekday,
        startTime,
        endTime,
        room: room.trim(),
      }),
    });
    setBusy(false);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setRoom('');
    setBanner({ kind: 'success', text: 'Routine entry created as DRAFT.' });
    await loadRoutine(sectionId, termId, statusFilter);
  }

  async function executeStatusAction() {
    if (!pendingAction) return;
    setBusy(true);
    const res = await proxyFetch<RoutineEntryItem>(
      `admin/routine/${pendingAction.id}/${pendingAction.kind}`,
      { method: 'POST' },
    );
    setBusy(false);
    setPendingAction(null);
    if (!res.success) {
      setBanner({ kind: 'error', text: res.error.message });
      return;
    }
    setBanner({ kind: 'success', text: `Routine entry ${res.data.status.toLowerCase()}.` });
    await loadRoutine(sectionId, termId, statusFilter);
  }

  const filteredDepts = (overview?.departments ?? []).filter(
    (d) => !programId || d.programId === programId,
  );
  const filteredTerms = (overview?.terms ?? []).filter(
    (t) => !sessionId || t.sessionId === sessionId,
  );
  const filteredBatches = (overview?.batches ?? []).filter(
    (b) =>
      (!departmentId || b.departmentId === departmentId) &&
      (!sessionId || b.sessionId === sessionId),
  );
  const filteredSections = (overview?.sections ?? []).filter(
    (s) => !batchId || s.batchId === batchId,
  );

  return (
    <AdminShell>
      <div className="mx-auto max-w-6xl space-y-6">
        <PageHeader
          breadcrumbs={[{ label: 'Overview', href: '/' }, { label: 'Routine Management' }]}
          icon={<Calendar className="h-6 w-6 text-slate-700" aria-hidden="true" />}
          title="Class Routine Management"
          description="Schedule section timetables with automatic teacher, section, and room overlap detection (Asia/Dhaka)."
        />

        {banner && <ErrorBanner kind={banner.kind} message={banner.text} />}

        {loading ? (
          <LoadingSkeleton rows={5} />
        ) : (
          <>
            <form
              onSubmit={(e) => void handleCreate(e)}
              className="space-y-3 rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-5"
            >
              <h2 className="flex items-center gap-2 text-sm font-semibold text-slate-900">
                <Plus className="h-4 w-4" aria-hidden="true" />
                <span>Add Timetable Slot</span>
              </h2>
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-3 lg:grid-cols-6">
                <select
                  aria-label="Subject Offering"
                  value={offeringId}
                  onChange={(e) => setOfferingId(e.target.value)}
                  className="rounded-lg border border-slate-300 bg-white px-2.5 py-2 text-xs"
                >
                  {(overview?.offerings ?? []).map((off) => (
                    <option key={off.id} value={off.id}>
                      {off.subject.code} • {off.section.code} ({off.term.name})
                    </option>
                  ))}
                </select>
                <select
                  aria-label="Assigned Teacher"
                  value={teacherId}
                  onChange={(e) => setTeacherId(e.target.value)}
                  className="rounded-lg border border-slate-300 bg-white px-2.5 py-2 text-xs"
                >
                  {teachers.map((t) => (
                    <option key={t.id} value={t.id}>
                      {t.fullName} ({t.department.code})
                    </option>
                  ))}
                </select>
                <select
                  aria-label="Weekday"
                  value={weekday}
                  onChange={(e) => setWeekday(e.target.value)}
                  className="rounded-lg border border-slate-300 bg-white px-2.5 py-2 text-xs"
                >
                  {WEEKDAYS.map((d) => (
                    <option key={d} value={d}>
                      {d}
                    </option>
                  ))}
                </select>
                <input
                  required
                  aria-label="Start Time"
                  type="time"
                  value={startTime}
                  onChange={(e) => setStartTime(e.target.value)}
                  className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                />
                <input
                  required
                  aria-label="End Time"
                  type="time"
                  value={endTime}
                  onChange={(e) => setEndTime(e.target.value)}
                  className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                />
                <input
                  required
                  aria-label="Room"
                  placeholder="Room (e.g. Room 302)"
                  value={room}
                  onChange={(e) => setRoom(e.target.value)}
                  className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                />
              </div>
              <button
                type="submit"
                disabled={busy}
                className="rounded-lg bg-slate-900 px-4 py-2 text-xs font-medium text-white hover:bg-slate-800 disabled:opacity-60"
              >
                Create Draft Slot
              </button>
            </form>

            <section
              aria-label="Routine filters"
              className="grid grid-cols-2 gap-3 rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-4 sm:grid-cols-4 lg:grid-cols-7"
            >
              <select
                aria-label="Program"
                value={programId}
                onChange={(e) => setProgramId(e.target.value)}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Programs</option>
                {(overview?.programs ?? []).map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.code}
                  </option>
                ))}
              </select>
              <select
                aria-label="Department"
                value={departmentId}
                onChange={(e) => setDepartmentId(e.target.value)}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Depts</option>
                {filteredDepts.map((d) => (
                  <option key={d.id} value={d.id}>
                    {d.code}
                  </option>
                ))}
              </select>
              <select
                aria-label="Session"
                value={sessionId}
                onChange={(e) => setSessionId(e.target.value)}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Sessions</option>
                {(overview?.sessions ?? []).map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.code}
                  </option>
                ))}
              </select>
              <select
                aria-label="Term"
                value={termId}
                onChange={(e) => {
                  const next = e.target.value;
                  setTermId(next);
                  void loadRoutine(sectionId, next, statusFilter);
                }}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Terms</option>
                {filteredTerms.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.name}
                  </option>
                ))}
              </select>
              <select
                aria-label="Batch"
                value={batchId}
                onChange={(e) => setBatchId(e.target.value)}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Batches</option>
                {filteredBatches.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.code}
                  </option>
                ))}
              </select>
              <select
                aria-label="Section"
                value={sectionId}
                onChange={(e) => {
                  const next = e.target.value;
                  setSectionId(next);
                  void loadRoutine(next, termId, statusFilter);
                }}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Sections</option>
                {filteredSections.map((sec) => (
                  <option key={sec.id} value={sec.id}>
                    {sec.name}
                  </option>
                ))}
              </select>
              <select
                aria-label="Status"
                value={statusFilter}
                onChange={(e) => {
                  const next = e.target.value;
                  setStatusFilter(next);
                  void loadRoutine(sectionId, termId, next);
                }}
                className="rounded-lg border border-slate-300 bg-white px-2 py-1.5 text-xs"
              >
                <option value="">All Statuses</option>
                <option value="DRAFT">DRAFT</option>
                <option value="PUBLISHED">PUBLISHED</option>
                <option value="ARCHIVED">ARCHIVED</option>
              </select>
            </section>

            {entries.length === 0 ? (
              <EmptyState
                icon={<Calendar className="h-8 w-8" aria-hidden="true" />}
                title="No Routine Slots Found"
                description="Create a timetable slot above or adjust the cohort filters."
              />
            ) : (
              <section className="overflow-hidden rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)]">
                <ul className="divide-y divide-slate-200">
                  {entries.map((entry) => (
                    <li
                      key={entry.id}
                      className="flex flex-wrap items-center justify-between gap-3 px-5 py-3.5 text-xs"
                    >
                      <div className="space-y-1">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="rounded bg-slate-900 px-2 py-0.5 font-semibold text-white">
                            {entry.weekday}
                          </span>
                          <span className="font-semibold text-slate-900">
                            {entry.startTime} – {entry.endTime}
                          </span>
                          <span className="font-medium text-slate-800">
                            {entry.subject.code} — {entry.subject.name}
                          </span>
                          <StatusBadge status={entry.status} />
                        </div>
                        <p className="text-slate-600">
                          {entry.department.code} • {entry.batch.code} ({entry.section.name}) • Room{' '}
                          {entry.room} • {entry.teacherProfile.user.fullName}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        {entry.status === 'DRAFT' && (
                          <button
                            type="button"
                            onClick={() =>
                              setPendingAction({
                                id: entry.id,
                                kind: 'publish',
                                label: `${entry.subject.code} (${entry.weekday} ${entry.startTime})`,
                              })
                            }
                            className="rounded-lg bg-emerald-700 px-3 py-1.5 font-medium text-white hover:bg-emerald-800"
                          >
                            Publish
                          </button>
                        )}
                        {entry.status !== 'ARCHIVED' && (
                          <button
                            type="button"
                            onClick={() =>
                              setPendingAction({
                                id: entry.id,
                                kind: 'archive',
                                label: `${entry.subject.code} (${entry.weekday} ${entry.startTime})`,
                              })
                            }
                            className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 font-medium text-slate-700 hover:bg-slate-50"
                          >
                            Archive
                          </button>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              </section>
            )}

            <section className="space-y-4 rounded-xl border border-[var(--saic-border)] bg-[var(--saic-surface)] p-5">
              <h2 className="text-sm font-semibold text-slate-900">
                Schedule Exceptions ({exceptions.length})
              </h2>
              <form
                onSubmit={(e) => void handleCreateException(e)}
                className="grid grid-cols-1 gap-3 sm:grid-cols-6"
              >
                <select
                  aria-label="Exception Routine Entry"
                  value={exEntryId}
                  onChange={(e) => setExEntryId(e.target.value)}
                  className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs sm:col-span-2"
                >
                  {entries.map((entry) => (
                    <option key={entry.id} value={entry.id}>
                      {entry.weekday} {entry.startTime} • {entry.subject.code} ({entry.section.code}
                      )
                    </option>
                  ))}
                </select>
                <input
                  required
                  aria-label="Exception Date"
                  type="date"
                  value={exDate}
                  onChange={(e) => setExDate(e.target.value)}
                  className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                />
                <select
                  aria-label="Exception Type"
                  value={exType}
                  onChange={(e) => setExType(e.target.value as 'CANCELLED' | 'RESCHEDULED')}
                  className="rounded-lg border border-slate-300 bg-white px-2.5 py-1.5 text-xs"
                >
                  <option value="CANCELLED">CANCELLED</option>
                  <option value="RESCHEDULED">RESCHEDULED</option>
                </select>
                <input
                  placeholder="Reason (optional)"
                  value={exReason}
                  onChange={(e) => setExReason(e.target.value)}
                  className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs sm:col-span-2"
                />
                {exType === 'RESCHEDULED' && (
                  <>
                    <input
                      required
                      aria-label="Override Start Time"
                      type="time"
                      value={exStartTime}
                      onChange={(e) => setExStartTime(e.target.value)}
                      className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                    />
                    <input
                      required
                      aria-label="Override End Time"
                      type="time"
                      value={exEndTime}
                      onChange={(e) => setExEndTime(e.target.value)}
                      className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs"
                    />
                    <input
                      placeholder="Override Room (optional)"
                      value={exRoom}
                      onChange={(e) => setExRoom(e.target.value)}
                      className="rounded-lg border border-slate-300 px-2.5 py-1.5 text-xs sm:col-span-2"
                    />
                  </>
                )}
                <button
                  type="submit"
                  disabled={busy || entries.length === 0}
                  className="rounded-lg bg-slate-900 px-3 py-1.5 text-xs font-medium text-white hover:bg-slate-800 disabled:opacity-50"
                >
                  Add Exception
                </button>
              </form>

              {exceptions.length > 0 && (
                <ul className="divide-y divide-slate-200 text-xs">
                  {exceptions.map((ex) => (
                    <li
                      key={ex.id}
                      className="flex flex-wrap items-center justify-between gap-2 py-2.5"
                    >
                      <div>
                        <span className="font-semibold text-slate-900">
                          {new Date(ex.exceptionDate).toISOString().slice(0, 10)}
                        </span>{' '}
                        <StatusBadge status={ex.type} />{' '}
                        <span className="text-slate-700">
                          {ex.routineEntry?.subject.code} ({ex.routineEntry?.section.code})
                          {ex.type === 'RESCHEDULED'
                            ? ` → ${ex.overrideStartTime}–${ex.overrideEndTime} (${ex.overrideRoom ?? ex.routineEntry?.room})`
                            : ''}
                        </span>
                        {ex.reason && <span className="ml-2 text-slate-500">• {ex.reason}</span>}
                      </div>
                      <button
                        type="button"
                        disabled={busy}
                        onClick={() => void handleDeleteException(ex.id)}
                        className="rounded border border-slate-300 bg-white px-2.5 py-1 font-medium text-slate-700 hover:bg-slate-50"
                      >
                        Remove
                      </button>
                    </li>
                  ))}
                </ul>
              )}
            </section>
          </>
        )}

        <ConfirmDialog
          open={pendingAction !== null}
          busy={busy}
          title={
            pendingAction?.kind === 'publish' ? 'Publish Routine Slot' : 'Archive Routine Slot'
          }
          message={`Are you sure you want to ${pendingAction?.kind} ${pendingAction?.label ?? ''}?`}
          confirmLabel={pendingAction?.kind === 'publish' ? 'Confirm Publish' : 'Confirm Archive'}
          onCancel={() => setPendingAction(null)}
          onConfirm={() => void executeStatusAction()}
        />
      </div>
    </AdminShell>
  );
}
