"use client";

import { useState } from "react";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ApiError } from "@/lib/api";
import type { ExportFormat } from "@/lib/export";
import {
  downloadAttendanceExport,
  type BoardExportKind,
  type BoardQuery,
} from "@/lib/attendance-report";

type ExportReport = {
  id: string;
  kind: BoardExportKind;
  title: string;
  hint: string;
  extra?: Partial<BoardQuery>;
};

/**
 * خروجی‌ها همان فیلترهای صفحه را می‌برند؛ هر قالب یک گزارش سرور است، پس
 * ستون‌ها و ترجمه‌ها یک‌جا در API نگه داشته می‌شود.
 */
const EXPORT_REPORTS: ExportReport[] = [
  {
    id: "branches",
    kind: "branches",
    title: "خلاصه وضعیت شعب",
    hint: "حاضر، تأخیر، غایب، ثبت‌نشده و تفکیک جلسات حضوری/مجازی هر شعبه",
  },
  {
    id: "students",
    kind: "students",
    title: "ریز حضور دانش‌آموزان",
    hint: "یک ردیف برای هر دانش‌آموز در هر جلسه، همراه نوع کلاس و وضعیت پیامک",
  },
  {
    id: "absent",
    kind: "students",
    title: "فهرست غایبان",
    hint: "فقط ردیف‌های غایب همین محدوده",
    extra: { status: "absent" },
  },
  {
    id: "unjustified",
    kind: "students",
    title: "غایبان بدون توجیه",
    hint: "غیبت‌هایی که گواهی یا توضیح ثبت‌شده ندارند",
    extra: { status: "unjustified" },
  },
  {
    id: "atrisk",
    kind: "students",
    title: "نزدیک سقف غیبت مجاز",
    hint: "دانش‌آموزانی که به آستانه سیاست گزارشگیری رسیده‌اند",
    extra: { status: "atrisk" },
  },
  {
    id: "unchecked",
    kind: "students",
    title: "حضور ثبت‌نشده",
    hint: "دانش‌آموزانی که وضعیت‌شان در کلاس ثبت نشده است",
    extra: { status: "unchecked" },
  },
  {
    id: "virtual-students",
    kind: "students",
    title: "ریز حضور کلاس‌های مجازی",
    hint: "فقط جلسات مجازی، آفلاین و ترکیبی",
    extra: { deliveryMode: "virtual" },
  },
  {
    id: "classes",
    kind: "classes",
    title: "تکمیل لیست حضور معلمان",
    hint: "هر جلسه با تعداد ثبت‌شده، تأخیر ارسال و نوع کلاس",
  },
  {
    id: "classes-delayed",
    kind: "classes",
    title: "تأخیر ارسال لیست معلمان",
    hint: "جلساتی که از آستانه ارسال فرم عبور کرده‌اند",
    extra: { lists: "delayed" },
  },
  {
    id: "classes-pending",
    kind: "classes",
    title: "لیست‌های ناقص و پرنشده",
    hint: "جلساتی که فرم حضور آن‌ها کامل نیست",
    extra: { lists: "pending" },
  },
];

const FORMATS: Array<{ key: ExportFormat; title: string; hint: string }> = [
  { key: "xlsx", title: "Excel", hint: "فایل قابل ویرایش برای تحلیل و پیوست گزارش هلدینگ" },
  { key: "pdf", title: "PDF", hint: "نسخه چاپی برای بازرسی و آموزش و پرورش" },
  { key: "csv", title: "CSV", hint: "برای ورود به ابزارهای دیگر" },
];

export function AttendanceExportMenu({
  query,
  scopeLabel,
  dateLabel,
  onClose,
}: {
  query: BoardQuery;
  scopeLabel: string;
  dateLabel: string;
  onClose: () => void;
}) {
  const [reportId, setReportId] = useState<string | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const report = EXPORT_REPORTS.find((item) => item.id === reportId) ?? null;

  async function run(format: ExportFormat) {
    if (!report) return;
    setBusy(format);
    setError(null);
    try {
      await downloadAttendanceExport(report.kind, { ...query, ...report.extra }, format);
      onClose();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در ساخت خروجی");
    } finally {
      setBusy(null);
    }
  }

  return (
    <>
      <button
        type="button"
        aria-label="بستن منوی خروجی"
        className="fixed inset-0 z-40 cursor-default"
        onClick={onClose}
      />
      <div className="absolute left-0 top-full z-50 mt-2 w-[min(23rem,calc(100vw-2.5rem))] overflow-hidden rounded-[1.3rem] border border-slate-200 bg-white text-right shadow-2xl">
        <div className="border-b border-slate-100 bg-slate-50/80 px-4 py-3">
          <p className="text-[11px] font-bold text-teal-700">
            {report ? "قالب فایل" : "چه خروجی می‌خواهید؟"}
          </p>
          <p className="mt-0.5 text-xs font-bold text-slate-700">
            {report ? report.title : "یکی از گزارش‌های زیر را انتخاب کنید"}
          </p>
          <p className="mt-0.5 text-[11px] text-slate-500">
            {scopeLabel} · {dateLabel}
          </p>
        </div>

        {error ? (
          <div className="p-3">
            <Alert tone="error">{error}</Alert>
          </div>
        ) : null}

        {report ? (
          <div className="p-3">
            <div className="grid gap-2">
              {FORMATS.map((format) => (
                <button
                  key={format.key}
                  type="button"
                  disabled={busy !== null}
                  onClick={() => void run(format.key)}
                  className="rounded-2xl bg-slate-50 px-4 py-3 text-right transition hover:bg-teal-50 disabled:opacity-60"
                >
                  <p className="text-sm font-bold text-slate-900">
                    {format.title}
                    {busy === format.key ? " · در حال ساخت…" : ""}
                  </p>
                  <p className="mt-0.5 text-[11px] text-slate-500">{format.hint}</p>
                </button>
              ))}
            </div>
            <div className="mt-3 flex gap-2">
              <Button block variant="secondary" onClick={() => setReportId(null)}>
                بازگشت
              </Button>
              <Button block variant="ghost" onClick={onClose}>
                انصراف
              </Button>
            </div>
          </div>
        ) : (
          <ul className="max-h-[22rem] overflow-y-auto p-2">
            {EXPORT_REPORTS.map((item) => (
              <li key={item.id}>
                <button
                  type="button"
                  onClick={() => setReportId(item.id)}
                  className="flex w-full items-start justify-between gap-2 rounded-xl px-3 py-2.5 text-right transition hover:bg-teal-50"
                >
                  <span className="min-w-0">
                    <span className="block text-sm font-bold text-slate-800">{item.title}</span>
                    <span className="mt-0.5 block text-[11px] leading-5 text-slate-500">
                      {item.hint}
                    </span>
                  </span>
                  <span aria-hidden className="mt-1 text-[11px] text-slate-400">
                    ‹
                  </span>
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    </>
  );
}
