"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { TeacherPanel } from "@/components/teacher/ui/TeacherPanel";
import { TeacherShell } from "@/components/teacher/TeacherShell";
import { ApiError, apiGet } from "@/lib/api";
import { SubjectAvatar } from "@/components/ui/SubjectAvatar";

interface WeeklyPayload {
  week_start: string;
  weekly_hours: number;
  days: Array<{
    date: string;
    day_name: string;
    total: number;
    items: Array<{
      schedule_id: number;
      class_room_id: number;
      subject_id?: number;
      subject_name?: string;
      subject_image_url?: string | null;
      class_code?: string;
      starts_at?: string;
      ends_at?: string;
    }>;
  }>;
}

interface NotificationItem {
  id: number;
  type: string;
  title: string;
  body?: string;
  read_at?: string | null;
  at?: string;
}

export default function TeacherProfilePage() {
  const [schedule, setSchedule] = useState<WeeklyPayload | null>(null);
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dayIndex, setDayIndex] = useState(() => {
    const dow = (new Date().getDay() + 1) % 7;
    return dow;
  });

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const [week, notifs] = await Promise.all([
        apiGet<WeeklyPayload>("/teacher/weekly-schedule"),
        apiGet<{ items: NotificationItem[] }>("/teacher/notifications"),
      ]);
      setSchedule(week);
      setNotifications(notifs.items ?? []);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  const activeDay = schedule?.days[dayIndex];

  return (
    <TeacherShell title="پرونده معلم" subtitle="برنامه و اعلان‌ها" showBack>
      {error ? <Alert tone="error">{error}</Alert> : null}
      {loading ? (
        <PageContentSkeleton rows={5} />
      ) : (
        <div className="space-y-4">
          <TeacherPanel>
            <div className="text-sm text-slate-500">ساعات تدریس هفتگی (تقریبی)</div>
            <div className="text-2xl font-bold">{schedule?.weekly_hours ?? 0} ساعت</div>
          </TeacherPanel>

          <div className="flex gap-1 overflow-x-auto">
            {schedule?.days.map((d, i) => (
              <button
                key={d.date}
                type="button"
                onClick={() => setDayIndex(i)}
                className={`shrink-0 rounded-xl px-3 py-2 text-sm font-semibold ${
                  dayIndex === i ? "bg-teal-600 text-white" : "bg-white border border-slate-200 text-slate-600"
                }`}
              >
                {d.day_name}
              </button>
            ))}
          </div>

          <TeacherPanel>
            <h3 className="mb-2 font-bold">{activeDay?.day_name} — {activeDay?.date}</h3>
            {!activeDay?.items.length ? (
              <p className="text-sm text-slate-400">کلاسی نیست.</p>
            ) : (
              <ul className="space-y-2 text-sm">
                {activeDay.items.map((item) => (
                  <li key={item.schedule_id} className="flex items-center justify-between gap-2 rounded-lg border border-slate-100 px-3 py-2">
                    <div className="flex min-w-0 items-center gap-2">
                      <SubjectAvatar
                        name={item.subject_name ?? "درس"}
                        imageUrl={item.subject_image_url}
                        size="sm"
                      />
                      <span className="truncate">
                        {item.subject_name} ({item.class_code})
                      </span>
                    </div>
                    <Link
                      href={`/teacher/classes/${item.class_room_id}?subject_id=${item.subject_id ?? ""}`}
                      className="text-teal-700 hover:underline"
                    >
                      {item.starts_at}–{item.ends_at}
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </TeacherPanel>

          <TeacherPanel>
            <h3 className="mb-2 font-bold">اعلان‌ها</h3>
            {notifications.length === 0 ? (
              <p className="text-sm text-slate-400">اعلانی نیست.</p>
            ) : (
              <ul className="space-y-2 text-sm">
                {notifications.map((n) => (
                  <li key={n.id} className={`rounded-lg px-3 py-2 ${n.read_at ? "text-slate-400" : "bg-teal-50 font-medium"}`}>
                    {n.title}
                    {n.body ? <div className="text-xs font-normal text-slate-500">{n.body}</div> : null}
                  </li>
                ))}
              </ul>
            )}
          </TeacherPanel>

          <Link href="/dashboard">
            <Button variant="secondary">بازگشت به داشبورد</Button>
          </Link>
        </div>
      )}
    </TeacherShell>
  );
}
