"use client";

import { useCallback, useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { PageHeader } from "@/components/layout/PageHeader";
import { DataTable, DataTableEmpty } from "@/components/layout/DataTable";
import { ActionMenu } from "@/components/layout/ActionMenu";
import { ListExportActions } from "@/components/export/ListExportActions";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { Field, Input } from "@/components/ui/Field";
import { PersianDatePicker } from "@/components/ui/PersianDatePicker";
import { ApiError, apiDelete, apiGet, apiPatch, apiPost, switchAcademicYear } from "@/lib/api";
import { formatJalaliDate } from "@/lib/jalali-month";

interface YearRow {
  id: number;
  title: string;
  starts_at: string;
  ends_at: string;
  is_current: boolean;
  is_active: boolean;
}

const emptyForm = {
  title: "",
  starts_at: "",
  ends_at: "",
  is_current: false,
};

export default function AcademicYearsPage() {
  const [rows, setRows] = useState<YearRow[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [loading, setLoading] = useState(false);
  const [listLoading, setListLoading] = useState(true);

  const load = useCallback(async () => {
    setListLoading(true);
    try {
      setRows(await apiGet<YearRow[]>("/academic-years"));
      setError(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setListLoading(false);
    }
  }, []);

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

  const openCreate = () => {
    setEditId(null);
    setForm(emptyForm);
    setShowForm(true);
  };

  const openEdit = (y: YearRow) => {
    setEditId(y.id);
    setForm({
      title: y.title,
      starts_at: y.starts_at?.slice(0, 10) ?? "",
      ends_at: y.ends_at?.slice(0, 10) ?? "",
      is_current: y.is_current,
    });
    setShowForm(true);
  };

  const submit = async () => {
    setLoading(true);
    setError(null);
    setMessage(null);
    try {
      if (editId) {
        await apiPatch(`/academic-years/${editId}`, {
          title: form.title,
          starts_at: form.starts_at,
          ends_at: form.ends_at,
        });
        setMessage("سال تحصیلی به‌روزرسانی شد.");
      } else {
        await apiPost("/academic-years", form);
        setMessage("سال تحصیلی ثبت شد.");
      }
      setShowForm(false);
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    } finally {
      setLoading(false);
    }
  };

  const setCurrent = async (id: number) => {
    try {
      await apiPatch(`/academic-years/${id}/set-current`, {});
      await switchAcademicYear(id);
      setMessage("سال تحصیلی جاری تنظیم شد.");
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const toggleActive = async (y: YearRow) => {
    try {
      await apiPatch(`/academic-years/${y.id}/${y.is_active ? "deactivate" : "activate"}`, {});
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  const remove = async (id: number) => {
    if (!confirm("آیا از حذف این سال تحصیلی مطمئن هستید؟")) return;
    try {
      await apiDelete(`/academic-years/${id}`);
      setMessage("سال تحصیلی حذف شد.");
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا");
    }
  };

  return (
    <AppShell title="سال تحصیلی" subtitle="مدیریت سال‌های تحصیلی سازمان">
      {error ? <Alert tone="error">{error}</Alert> : null}
      {message ? <Alert tone="success">{message}</Alert> : null}

      <PageHeader
        title="فهرست سال‌های تحصیلی"
        subtitle={`تعداد: ${rows.length}`}
        actions={
          <>
            <ListExportActions
              exportPath="/academic-years/export"
              filters={{}}
              filenameBase="academic-years-export"
              onError={setError}
            />
            <Button onClick={openCreate}>+ ثبت سال تحصیلی جدید</Button>
          </>
        }
      />

      {showForm ? (
        <div className="mb-4 rounded-2xl border border-[var(--border)] bg-white p-4">
          <h3 className="mb-3 font-bold">{editId ? "ویرایش سال تحصیلی" : "ثبت سال تحصیلی"}</h3>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            <Field label="عنوان">
              <Input
                value={form.title}
                placeholder="مثلاً 1405-1406"
                onChange={(e) => setForm({ ...form, title: e.target.value })}
              />
            </Field>
            <Field label="تاریخ شروع">
              <PersianDatePicker
                value={form.starts_at}
                onChange={(starts_at) => setForm({ ...form, starts_at })}
              />
            </Field>
            <Field label="تاریخ پایان">
              <PersianDatePicker
                value={form.ends_at}
                onChange={(ends_at) => setForm({ ...form, ends_at })}
              />
            </Field>
            {!editId ? (
              <label className="flex items-center gap-2 text-sm sm:col-span-2 lg:col-span-3">
                <input
                  type="checkbox"
                  checked={form.is_current}
                  onChange={(e) => setForm({ ...form, is_current: e.target.checked })}
                />
                تنظیم به‌عنوان سال تحصیلی جاری
              </label>
            ) : null}
          </div>
          <div className="mt-3 flex gap-2">
            <Button loading={loading} onClick={submit}>ذخیره</Button>
            <Button variant="secondary" onClick={() => setShowForm(false)}>انصراف</Button>
          </div>
        </div>
      ) : null}

      <DataTable
        loading={listLoading}
        columns={[
          { key: "idx", label: "#" },
          { key: "title", label: "عنوان" },
          { key: "start", label: "شروع" },
          { key: "end", label: "پایان" },
          { key: "status", label: "وضعیت" },
          { key: "current", label: "جاری" },
          { key: "ops", label: "عملیات" },
        ]}
      >
        {rows.length === 0 ? (
          <DataTableEmpty colSpan={7} />
        ) : (
          rows.map((y, i) => (
            <tr key={y.id} className="hover:bg-slate-50">
              <td className="px-3 py-3">{i + 1}</td>
              <td className="px-3 py-3 font-medium">{y.title}</td>
              <td className="px-3 py-3 text-xs">{formatJalaliDate(y.starts_at)}</td>
              <td className="px-3 py-3 text-xs">{formatJalaliDate(y.ends_at)}</td>
              <td className="px-3 py-3">
                <span
                  className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
                    y.is_active ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"
                  }`}
                >
                  {y.is_active ? "فعال" : "غیرفعال"}
                </span>
              </td>
              <td className="px-3 py-3">
                {y.is_current ? (
                  <span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-800">
                    سال جاری
                  </span>
                ) : (
                  "—"
                )}
              </td>
              <td className="px-3 py-3">
                <ActionMenu
                  items={[
                    { label: "ویرایش", onClick: () => openEdit(y) },
                    ...(y.is_active && !y.is_current
                      ? [{ label: "انتخاب به‌عنوان سال جاری", onClick: () => setCurrent(y.id) }]
                      : []),
                    ...(!y.is_current
                      ? [{ label: y.is_active ? "غیرفعال کردن" : "فعال کردن", onClick: () => toggleActive(y) }]
                      : []),
                    ...(!y.is_current
                      ? [{ label: "حذف", onClick: () => remove(y.id), tone: "danger" as const }]
                      : []),
                  ]}
                />
              </td>
            </tr>
          ))
        )}
      </DataTable>
    </AppShell>
  );
}
