"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  EmptyState,
  Input,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatCard,
  StatusBadge,
  Textarea,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { PROMOTION_TYPES } from "@/lib/constants";
import { IconTrend, IconUsers } from "@/components/icons";

interface Item {
  id: number;
  category: string;
  name: string;
  nameBn: string;
}

interface StudentRow {
  id: number;
  roll: string;
  name: string;
  classItemId: number | null;
  sectionItemId: number | null;
  shiftItemId: number | null;
  groupItemId: number | null;
  className: string | null;
  sectionName: string | null;
  shiftName: string | null;
  groupName: string | null;
}

interface HistoryRow {
  id: number;
  studentId: number;
  roll: string;
  studentName: string;
  promoteType: string;
  fromName: string | null;
  toName: string | null;
  note: string | null;
  promotedBy: string | null;
  promotedAt: string;
}

interface PromoData {
  items: Item[];
  students: StudentRow[];
  history: HistoryRow[];
}

type Tab = "promote" | "history";
type PromoType = "CLASS" | "SECTION" | "SHIFT" | "GROUP";

const CATEGORY_BY_TYPE: Record<PromoType, string> = {
  CLASS: "CLASS",
  SECTION: "SECTION",
  SHIFT: "SHIFT",
  GROUP: "GROUP",
};

const currentKey: Record<PromoType, keyof StudentRow> = {
  CLASS: "classItemId",
  SECTION: "sectionItemId",
  SHIFT: "shiftItemId",
  GROUP: "groupItemId",
};
const currentLabel: Record<PromoType, keyof StudentRow> = {
  CLASS: "className",
  SECTION: "sectionName",
  SHIFT: "shiftName",
  GROUP: "groupName",
};

export default function PortalPromotionsPage() {
  const { t, locale } = useLang();
  const [tab, setTab] = useState<Tab>("promote");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const { data, loading, reload } = useApi<PromoData>("/api/portal/promotions");

  const [promoteType, setPromoteType] = useState<PromoType>("CLASS");
  const [toItemId, setToItemId] = useState("");
  const [note, setNote] = useState("");
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState("");
  const [historyFilter, setHistoryFilter] = useState("");

  const cat = CATEGORY_BY_TYPE[promoteType];
  const items = useMemo(
    () => (data?.items ?? []).filter((i) => i.category === cat),
    [data, cat]
  );

  const students = useMemo(() => {
    if (!data) return [];
    const q = search.trim().toLowerCase();
    const list = q
      ? data.students.filter(
          (st) => st.name.toLowerCase().includes(q) || st.roll.toLowerCase().includes(q)
        )
      : data.students;
    return list;
  }, [data, search]);

  const history = useMemo(() => {
    if (!data) return [];
    const q = historyFilter.trim().toLowerCase();
    if (!q) return data.history;
    return data.history.filter(
      (h) =>
        h.studentName.toLowerCase().includes(q) ||
        h.roll.toLowerCase().includes(q) ||
        (h.toName ?? "").toLowerCase().includes(q)
    );
  }, [data, historyFilter]);

  const studentsPager = usePagination(students, 10);
  const historyPager = usePagination(history, 10);

  function toggle(id: number) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function toggleAll() {
    setSelected((prev) => (prev.size === students.length ? new Set() : new Set(students.map((s) => s.id))));
  }

  async function promote() {
    if (!toItemId || selected.size === 0) return;
    setSaving(true);
    try {
      const res = await api<{ promoted: number }>("/api/portal/promotions", {
        method: "POST",
        body: JSON.stringify({
          promoteType,
          toItemId: Number(toItemId),
          studentIds: Array.from(selected),
          note,
        }),
      });
      setSelected(new Set());
      setNote("");
      reload();
      notify("success", `${t.portal.promotionsPage.promotedCount}: ${res.promoted}`);
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify("error", err === "ALREADY_SET" ? t.portal.promotionsPage.alreadySet : t.common.tryAgain);
    } finally {
      setSaving(false);
    }
  }

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  if (loading) return <PageLoader text={t.common.loading} />;
  const h = data?.history ?? [];

  return (
    <div>
      <PageHeader
        title={t.portal.promotionsPage.title}
        subtitle={t.portal.promotionsPage.subtitle}
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      <div className="row g-3 mb-4">
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.promotionsPage.totalPromotions} value={String(h.length)} icon={<IconTrend />} accent="teal" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.promotionsPage.classPromotions} value={String(h.filter((x) => x.promoteType === "CLASS").length)} icon={<IconTrend />} accent="sky" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.promotionsPage.sectionPromotions} value={String(h.filter((x) => x.promoteType === "SECTION").length)} icon={<IconTrend />} accent="purple" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.promotionsPage.otherPromotions} value={String(h.filter((x) => x.promoteType === "SHIFT" || x.promoteType === "GROUP").length)} icon={<IconTrend />} accent="orange" />
        </div>
      </div>

      <ul className="nav nav-tabs mb-4" role="tablist">
        {(["promote", "history"] as Tab[]).map((key) => {
          const labels: Record<Tab, string> = {
            promote: t.portal.promotionsPage.tabPromote,
            history: t.portal.promotionsPage.tabHistory,
          };
          return (
            <li className="nav-item" key={key}>
              <button className={`nav-link ${tab === key ? "active" : ""}`} onClick={() => setTab(key)} type="button">
                {labels[key]}
              </button>
            </li>
          );
        })}
      </ul>

      {/* ---------- Promote tab ---------- */}
      {tab === "promote" && (
        <div className="row g-4">
          <div className="col-xl-4">
            <Card title={t.portal.promotionsPage.promoteTitle} icon={<IconTrend className="svg-18" />}>
              <Select
                label={t.portal.promotionsPage.promoteType}
                value={promoteType}
                onChange={(e) => {
                  setPromoteType(e.target.value as PromoType);
                  setToItemId("");
                  setSelected(new Set());
                }}
              >
                {PROMOTION_TYPES.map((ty) => (
                  <option key={ty} value={ty}>
                    {t.promotionTypes[ty]}
                  </option>
                ))}
              </Select>
              <Select
                label={t.portal.promotionsPage.promoteTo}
                value={toItemId}
                onChange={(e) => setToItemId(e.target.value)}
              >
                <option value="">— {t.common.filter} —</option>
                {items.map((i) => (
                  <option key={i.id} value={i.id}>
                    {locale === "bn" ? i.nameBn : i.name}
                  </option>
                ))}
              </Select>
              <Textarea label={`${t.common.note} (${t.common.optional})`} value={note} onChange={(e) => setNote(e.target.value)} />
              <p className="ems-fs-11 text-muted mb-3">{t.portal.promotionsPage.selectionNote}</p>
              <Button onClick={promote} loading={saving} disabled={!toItemId || selected.size === 0}>
                <IconTrend className="svg-16" />
                <span className="ms-1">
                  {t.portal.promotionsPage.promoteBtn} ({selected.size})
                </span>
              </Button>
            </Card>
          </div>

          <div className="col-xl-8">
            <div className="card">
              <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
                <div className="has-search" style={{ maxWidth: 280 }}>
                  <span className="fa fa-search form-control-feedback" />
                  <input
                    className="form-control"
                    placeholder={t.common.search}
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                  />
                </div>
                <label className="d-flex align-items-center gap-2 ems-fs-13 f-w-600 cursor-pointer mb-0">
                  <input
                    type="checkbox"
                    className="form-check-input mt-0"
                    checked={students.length > 0 && selected.size === students.length}
                    onChange={toggleAll}
                  />
                  {t.portal.promotionsPage.selectAll}
                </label>
              </div>
              {students.length === 0 ? (
                <EmptyState icon={<IconUsers />} title={t.common.noData} />
              ) : (
                <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th style={{ width: 40 }}></th>
                        <th>{t.portal.studentsPage.rollNo}</th>
                        <th>{t.common.name}</th>
                        <th>{t.promotionTypes[promoteType]}</th>
                        <th>{t.common.status}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {studentsPager.paged.map((st) => {
                        const current = st[currentKey[promoteType]];
                        const label = (st[currentLabel[promoteType]] as string | null) ?? "—";
                        const willChange = !!toItemId && current !== Number(toItemId);
                        return (
                          <tr key={st.id} className={selected.has(st.id) ? "ems-row-selected" : ""}>
                            <td>
                              <input
                                type="checkbox"
                                className="form-check-input mt-0"
                                checked={selected.has(st.id)}
                                onChange={() => toggle(st.id)}
                              />
                            </td>
                            <td>
                              <span className="ems-roll-badge">{st.roll}</span>
                            </td>
                            <td className="f-w-600">{st.name}</td>
                            <td className="ems-fs-13">{label}</td>
                            <td>
                              {selected.has(st.id) && willChange ? (
                                <span className="badge badge-success">
                                  {t.portal.promotionsPage.willPromote}
                                </span>
                              ) : selected.has(st.id) && !willChange ? (
                                <span className="badge badge-secondary">{t.portal.promotionsPage.noChange}</span>
                              ) : (
                                <span className="ems-fs-12 text-muted">—</span>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
              <Pagination {...studentsPager} onPageChange={studentsPager.setPage} onSizeChange={studentsPager.setSize} />
            </div>
          </div>
        </div>
      )}

      {/* ---------- History tab ---------- */}
      {tab === "history" && (
        <div className="card">
          <div className="card-header">
            <div className="has-search" style={{ maxWidth: 300 }}>
              <span className="fa fa-search form-control-feedback" />
              <input
                className="form-control"
                placeholder={t.portal.promotionsPage.searchHistory}
                value={historyFilter}
                onChange={(e) => setHistoryFilter(e.target.value)}
              />
            </div>
          </div>
          {history.length === 0 ? (
            <EmptyState icon={<IconTrend />} title={t.portal.promotionsPage.noHistory} />
          ) : (
            <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.common.students}</th>
                    <th>{t.portal.promotionsPage.promoteType}</th>
                    <th>{t.portal.promotionsPage.fromTo}</th>
                    <th>{t.common.note}</th>
                    <th>{t.common.date}</th>
                  </tr>
                </thead>
                <tbody>
                  {historyPager.paged.map((row) => (
                    <tr key={row.id}>
                      <td>
                        <p className="mb-0 f-w-700">
                          {row.roll} — {row.studentName}
                        </p>
                        {row.promotedBy && (
                          <p className="mb-0 ems-fs-11 text-muted">
                            {t.portal.promotionsPage.by}: {row.promotedBy}
                          </p>
                        )}
                      </td>
                      <td>
                        <StatusBadge
                          status={row.promoteType}
                          label={t.promotionTypes[row.promoteType as keyof typeof t.promotionTypes] ?? row.promoteType}
                        />
                      </td>
                      <td className="ems-fs-13">
                        {row.fromName ?? "—"} <IconTrend className="svg-14" /> {row.toName ?? "—"}
                      </td>
                      <td className="ems-fs-12">{row.note ?? "—"}</td>
                      <td className="ems-fs-13">{formatDate(row.promotedAt, locale)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
          <Pagination {...historyPager} onPageChange={historyPager.setPage} onSizeChange={historyPager.setSize} />
        </div>
      )}
    </div>
  );
}
