"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 { StudentAvatar } from "@/components/teacher/StudentAvatar";
import { TeacherModal } from "@/components/teacher/ui/TeacherModal";
import { ApiError, apiGet } from "@/lib/api";

interface SnapshotResponse {
  student: {
    id: number;
    student_code?: string | null;
    first_name?: string | null;
    last_name?: string | null;
    enrollment_id?: number | null;
    father_name?: string | null;
  };
  class_room?: {
    id: number;
    name: string;
    code?: string | null;
    grade_level_name?: string | null;
  } | null;
  attendance_today?: { status: string; late_minutes?: number | null } | null;
  date: string;
}

interface RecentPayload {
  attendances: Array<{
    id: number;
    date: string;
    status: string;
    late_minutes?: number | null;
    subject_name?: string | null;
  }>;
  scores: Array<{
    id: number;
    title?: string | null;
    score: number;
    max_score: number;
    date?: string | null;
  }>;
  assignments: Array<{
    id: number;
    title: string;
    date?: string | null;
    max_score: number;
    score?: number | null;
    status: string;
  }>;
}

type HistoryTab = "attendance" | "grades" | "assignments";

const STATUS_LABELS: Record<string, string> = {
  present: "حاضر",
  absent: "غایب",
  late: "تأخیر",
  temporary_exit: "خروج موقت",
};

const ASSIGNMENT_STATUS: Record<string, string> = {
  submitted: "ارسال شده",
  graded: "نمره‌دهی شده",
  returned: "برگشت خورده",
  missing: "ارسال نشده",
  pending: "در انتظار",
  draft: "پیش‌نویس",
};

const TABS: Array<{ id: HistoryTab; label: string }> = [
  { id: "attendance", label: "حضورغیاب" },
  { id: "grades", label: "نمرات" },
  { id: "assignments", label: "تکالیف" },
];

function formatFaDate(iso?: string | null) {
  if (!iso) return "—";
  try {
    return new Date(iso.slice(0, 10) + "T12:00:00").toLocaleDateString("fa-IR", {
      weekday: "short",
      month: "short",
      day: "numeric",
    });
  } catch {
    return iso;
  }
}

function attendanceLabel(item: RecentPayload["attendances"][number]) {
  if (item.status === "late" && item.late_minutes) return `تأخیر ${item.late_minutes} دقیقه`;
  return STATUS_LABELS[item.status] ?? item.status;
}

function badgeClass(status: string) {
  if (status === "present") return "bg-emerald-100 text-emerald-800";
  if (status === "absent") return "bg-orange-100 text-orange-800";
  if (status === "late") return "bg-violet-100 text-violet-800";
  if (status === "temporary_exit") return "bg-amber-100 text-amber-800";
  if (status === "graded") return "bg-emerald-100 text-emerald-800";
  if (status === "submitted") return "bg-sky-100 text-sky-800";
  if (status === "missing") return "bg-slate-100 text-slate-600";
  return "bg-slate-100 text-slate-600";
}

export function StudentQuickModal({
  studentProfileId,
  classRoomId,
  subjectId,
  date,
  onClose,
}: {
  studentProfileId: number | null;
  classRoomId?: number;
  subjectId?: number | null;
  date?: string;
  onClose: () => void;
}) {
  const [data, setData] = useState<SnapshotResponse | null>(null);
  const [recent, setRecent] = useState<RecentPayload | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [tab, setTab] = useState<HistoryTab>("attendance");

  const load = useCallback(async () => {
    if (!studentProfileId) return;
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (classRoomId) params.set("class_room_id", String(classRoomId));
      if (date) params.set("date", date);
      const qs = params.toString();

      const recentParams = new URLSearchParams({ limit: "4" });
      if (classRoomId) recentParams.set("class_room_id", String(classRoomId));
      if (subjectId) recentParams.set("subject_id", String(subjectId));

      const [snapshot, history] = await Promise.all([
        apiGet<SnapshotResponse>(`/teacher/students/${studentProfileId}/snapshot${qs ? `?${qs}` : ""}`),
        apiGet<RecentPayload>(`/teacher/students/${studentProfileId}/recent?${recentParams}`),
      ]);
      setData(snapshot);
      setRecent(history);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setLoading(false);
    }
  }, [studentProfileId, classRoomId, subjectId, date]);

  useEffect(() => {
    if (studentProfileId) {
      setTab("attendance");
      void load();
    } else {
      setData(null);
      setRecent(null);
    }
  }, [studentProfileId, load]);

  const name = data
    ? [data.student.first_name, data.student.last_name].filter(Boolean).join(" ") || "—"
    : "";

  const attendanceToday = data?.attendance_today
    ? data.attendance_today.status === "late" && data.attendance_today.late_minutes
      ? `تأخیر ${data.attendance_today.late_minutes} دقیقه`
      : STATUS_LABELS[data.attendance_today.status] ?? data.attendance_today.status
    : "ثبت نشده";

  const list =
    tab === "attendance"
      ? recent?.attendances ?? []
      : tab === "grades"
        ? recent?.scores ?? []
        : recent?.assignments ?? [];

  return (
    <TeacherModal
      open={studentProfileId != null}
      onClose={onClose}
      title={name || "دانش‌آموز"}
      subtitle={data?.student.student_code ? `کد: ${data.student.student_code}` : undefined}
      size="lg"
    >
      {error ? <Alert tone="error">{error}</Alert> : null}
      {loading ? (
        <PageContentSkeleton rows={4} />
      ) : data ? (
        <div className="space-y-4">
          <div className="flex items-center gap-3">
            <StudentAvatar firstName={data.student.first_name} lastName={data.student.last_name} size="lg" />
            <div>
              <div className="font-semibold">{name}</div>
              <div className="text-sm text-[var(--muted)]">نام پدر: {data.student.father_name || "—"}</div>
              {data.class_room ? (
                <div className="text-sm text-[var(--muted)]">
                  {data.class_room.code ?? data.class_room.name}
                  {data.class_room.grade_level_name ? ` · ${data.class_room.grade_level_name}` : ""}
                </div>
              ) : null}
            </div>
          </div>

          <div className="rounded-2xl border border-slate-200 bg-slate-50 p-3 text-sm">
            <div className="text-xs text-[var(--muted)]">حضور امروز</div>
            <div className="mt-1 font-semibold">{attendanceToday}</div>
          </div>

          <div className="flex gap-1 rounded-2xl border border-slate-200 bg-slate-50 p-1">
            {TABS.map((item) => (
              <button
                key={item.id}
                type="button"
                onClick={() => setTab(item.id)}
                className={`flex-1 rounded-xl px-2 py-2 text-xs font-semibold transition sm:text-sm ${
                  tab === item.id ? "bg-primary text-white shadow-sm" : "text-slate-600 hover:bg-white"
                }`}
              >
                {item.label}
              </button>
            ))}
          </div>

          {list.length === 0 ? (
            <p className="text-xs text-slate-400">سابقه‌ای یافت نشد.</p>
          ) : tab === "attendance" ? (
            <ul className="space-y-1.5">
              {(recent?.attendances ?? []).map((item) => (
                <li
                  key={item.id}
                  className="flex items-center justify-between gap-2 rounded-xl border border-slate-100 px-3 py-2 text-xs"
                >
                  <div className="min-w-0">
                    <div className="font-semibold text-slate-800">{formatFaDate(item.date)}</div>
                    {item.subject_name ? (
                      <div className="truncate text-[11px] text-slate-400">{item.subject_name}</div>
                    ) : null}
                  </div>
                  <span className={`shrink-0 rounded-lg px-2 py-0.5 font-semibold ${badgeClass(item.status)}`}>
                    {attendanceLabel(item)}
                  </span>
                </li>
              ))}
            </ul>
          ) : tab === "grades" ? (
            <ul className="space-y-1.5">
              {(recent?.scores ?? []).map((item) => (
                <li
                  key={item.id}
                  className="flex items-center justify-between gap-2 rounded-xl border border-slate-100 px-3 py-2 text-xs"
                >
                  <div className="min-w-0">
                    <div className="truncate font-semibold text-slate-800">{item.title || "ارزیابی"}</div>
                    <div className="text-[11px] text-slate-400">{formatFaDate(item.date)}</div>
                  </div>
                  <span className="shrink-0 rounded-lg bg-emerald-100 px-2 py-0.5 font-semibold text-emerald-800">
                    {item.score} از {item.max_score}
                  </span>
                </li>
              ))}
            </ul>
          ) : (
            <ul className="space-y-1.5">
              {(recent?.assignments ?? []).map((item) => (
                <li
                  key={item.id}
                  className="flex items-center justify-between gap-2 rounded-xl border border-slate-100 px-3 py-2 text-xs"
                >
                  <div className="min-w-0">
                    <div className="truncate font-semibold text-slate-800">{item.title}</div>
                    <div className="text-[11px] text-slate-400">{formatFaDate(item.date)}</div>
                  </div>
                  <div className="flex shrink-0 flex-col items-end gap-0.5">
                    <span className={`rounded-lg px-2 py-0.5 font-semibold ${badgeClass(item.status)}`}>
                      {ASSIGNMENT_STATUS[item.status] ?? item.status}
                    </span>
                    {item.score != null ? (
                      <span className="text-[11px] text-slate-500">
                        {item.score} از {item.max_score}
                      </span>
                    ) : null}
                  </div>
                </li>
              ))}
            </ul>
          )}

          <Link href={`/students/${data.student.id}?class_room_id=${classRoomId ?? ""}`}>
            <Button block className="rounded-xl">
              مشاهده پروفایل
            </Button>
          </Link>
        </div>
      ) : null}
    </TeacherModal>
  );
}
