"use client";

import { useCallback, useEffect, useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input, Textarea } from "@/components/ui/Field";
import { PersianDatePicker } from "@/components/ui/PersianDatePicker";
import { PageContentSkeleton } from "@/components/ui/Skeleton";
import { TeacherEmptyState } from "@/components/teacher/ui/TeacherEmptyState";
import { TeacherPanel } from "@/components/teacher/ui/TeacherPanel";
import { TeacherStatGrid } from "@/components/teacher/ui/TeacherStatGrid";
import { ApiError, apiGet } from "@/lib/api";

interface ExamItem {
  id: number;
  title: string;
  type?: string | null;
  assessment_date?: string | null;
  subject_id?: number | null;
  subject_name?: string | null;
  max_score?: number | string;
}

const TYPE_LABELS: Record<string, string> = {
  exam: "آزمون",
  quiz: "کوییز",
  oral: "شفاهی",
  homework: "تکلیف",
  other: "سایر",
};

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

export function ClassExamsTab({
  classRoomId,
  subjectId,
}: {
  classRoomId: number;
  subjectId?: number | null;
}) {
  const [allSubjects, setAllSubjects] = useState(false);
  const [items, setItems] = useState<ExamItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [draftDate, setDraftDate] = useState("");
  const [draftTitle, setDraftTitle] = useState("");
  const [draftNote, setDraftNote] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams();
      if (!allSubjects && subjectId) params.set("subject_id", String(subjectId));
      const qs = params.toString();
      const rows = await apiGet<ExamItem[]>(
        `/teacher/classes/${classRoomId}/assessments${qs ? `?${qs}` : ""}`,
      );
      setItems(rows ?? []);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری آزمون‌ها");
    } finally {
      setLoading(false);
    }
  }, [allSubjects, classRoomId, subjectId]);

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

  return (
    <div className="space-y-4">
      {error ? <Alert tone="error">{error}</Alert> : null}

      <TeacherStatGrid
        items={[
          {
            key: "count",
            label: allSubjects ? "آزمون همه دروس" : "آزمون این درس",
            value: items.length,
            className: "border-violet-200 bg-violet-50/70",
            accent: "#7c3aed",
          },
        ]}
      />

      <div className="flex flex-wrap items-center justify-between gap-2">
        <h2 className="text-base font-bold text-slate-900">آزمون‌های این کلاس</h2>
        <Button
          variant={allSubjects ? "primary" : "secondary"}
          className="rounded-xl"
          onClick={() => setAllSubjects((v) => !v)}
        >
          {allSubjects ? "فقط درس جاری" : "مشاهده آزمون‌های همه دروس"}
        </Button>
      </div>

      {loading ? (
        <PageContentSkeleton rows={4} />
      ) : !items.length ? (
        <TeacherEmptyState
          title="آزمونی ثبت نشده"
          description={allSubjects ? "برای این کلاس آزمونی نیست." : "برای این درس آزمونی ثبت نشده است."}
        />
      ) : (
        <TeacherPanel padded={false}>
          <div className="overflow-x-auto">
            <table className="min-w-full text-sm">
              <thead className="bg-slate-50 text-slate-500">
                <tr>
                  <th className="px-4 py-3 text-right font-semibold">عنوان</th>
                  <th className="px-4 py-3 text-right font-semibold">تاریخ</th>
                  <th className="px-4 py-3 text-right font-semibold">درس</th>
                  <th className="px-4 py-3 text-right font-semibold">نوع</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => (
                  <tr key={item.id} className="border-t border-slate-100 hover:bg-slate-50/70">
                    <td className="px-4 py-3 font-semibold text-slate-900">{item.title}</td>
                    <td className="px-4 py-3 text-slate-600">{formatFaDate(item.assessment_date)}</td>
                    <td className="px-4 py-3">
                      <span className="rounded-full bg-teal-50 px-2.5 py-1 text-xs font-semibold text-teal-800">
                        {item.subject_name ?? "—"}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className="rounded-full bg-violet-50 px-2.5 py-1 text-xs font-semibold text-violet-800">
                        {TYPE_LABELS[item.type ?? ""] ?? item.type ?? "آزمون"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </TeacherPanel>
      )}

      <TeacherPanel>
        <div className="mb-3 flex items-center justify-between gap-2">
          <h3 className="text-sm font-bold text-slate-800">تعیین زمان آزمون کلاسی</h3>
          <span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-semibold text-amber-800">
            به زودی
          </span>
        </div>
        <p className="mb-4 text-xs text-slate-500">
          در فاز بعد معلم می‌تواند تاریخ، عنوان و توضیحات آزمون کلاسی را ذخیره کند.
        </p>
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="تاریخ">
            <PersianDatePicker value={draftDate} onChange={(v) => setDraftDate(v ?? "")} />
          </Field>
          <Field label="عنوان">
            <Input value={draftTitle} onChange={(e) => setDraftTitle(e.target.value)} placeholder="مثلاً آزمون میان‌ترم" />
          </Field>
        </div>
        <div className="mt-3">
          <Field label="توضیحات">
            <Textarea rows={3} value={draftNote} onChange={(e) => setDraftNote(e.target.value)} placeholder="توضیحات آزمون" />
          </Field>
        </div>
        <Button className="mt-4 rounded-xl" disabled>
          ثبت زمان آزمون
        </Button>
      </TeacherPanel>

      <TeacherPanel padded={false}>
        <div className="flex items-center justify-between gap-2 border-b border-slate-100 px-4 py-3">
          <h3 className="text-sm font-bold text-slate-800">مشاهده آزمون‌های کلاس</h3>
          <span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-semibold text-amber-800">
            به زودی
          </span>
        </div>
        <p className="px-4 pt-3 text-xs text-slate-500">
          آزمون‌های این کلاس در همه پایه‌ها با عنوان و تاریخ اینجا می‌آید.
        </p>
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="bg-slate-50 text-slate-500">
              <tr>
                <th className="px-4 py-3 text-right font-semibold">عنوان آزمون</th>
                <th className="px-4 py-3 text-right font-semibold">تاریخ</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td colSpan={2} className="px-4 py-8 text-center text-sm text-slate-400">
                  این بخش در فازهای بعدی تکمیل می‌شود.
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </TeacherPanel>
    </div>
  );
}
