"use client";

import { Fragment, useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Select,
  Textarea,
  EmptyState,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { INSTITUTION_TYPES } from "@/lib/constants";
import { formatBDT, formatNumber } from "@/lib/utils";
import { emsConfirm } from "@/components/ConfirmDialog";
import {
  EDUCATION_PATTERNS,
  EducationPattern,
  PATTERN_BY_ID,
  estimateCost,
} from "@/lib/pricing";
import {
  IconAcademic,
  IconBan,
  IconBuilding,
  IconCheck,
  IconEdit,
  IconPackage,
  IconPlus,
  IconSparkle,
  IconTrash,
} from "@/components/icons";

interface Plan {
  id: number;
  name: string;
  nameBn: string;
  institutionType: string;
  price: string;
  durationMonths: number;
  maxStudents: number;
  features: string[];
  featuresBn: string[];
  isActive: boolean;
  educationPattern?: string | null;
  billingBasis?: string | null;
  ratePerStudent?: string | null;
  yearlyDiscountPct?: number | null;
  _count: { requests: number; subscriptions: number };
}

const emptyForm = {
  name: "",
  nameBn: "",
  institutionType: "HIGH_SCHOOL",
  price: "",
  durationMonths: "12",
  maxStudents: "",
  features: "",
  featuresBn: "",
  yearlyDiscountPct: "10",
};

/** live pattern view of a plan row — DB rate/discount win, catalog fills gaps */
function planPattern(plan: Plan): EducationPattern | null {
  if (!plan.educationPattern) return null;
  const base = PATTERN_BY_ID[plan.educationPattern];
  if (!base) return null;
  return {
    ...base,
    rate: plan.ratePerStudent !== null && plan.ratePerStudent !== undefined ? Number(plan.ratePerStudent) : base.rate,
    yearlyDiscountPct:
      plan.yearlyDiscountPct === null || plan.yearlyDiscountPct === undefined
        ? base.yearlyDiscountPct
        : plan.yearlyDiscountPct,
  };
}

const GROUP_ORDER = ["GOVERNMENT", "SCHOOLS", "HIGHER", "SPECIAL"] as const;

export default function CentralPackagesPage() {
  const { t, locale } = useLang();
  const { data, loading, reload } = useApi<{ plans: Plan[] }>("/api/central/packages");
  const [calcStudents, setCalcStudents] = useState(300);
  const [legacyOpen, setLegacyOpen] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Plan | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [saving, setSaving] = useState(false);

  const { patternPlans, legacyPlans } = useMemo(() => {
    const list = data?.plans ?? [];
    return {
      patternPlans: list.filter((p) => p.educationPattern && PATTERN_BY_ID[p.educationPattern]),
      legacyPlans: list.filter((p) => !(p.educationPattern && PATTERN_BY_ID[p.educationPattern])),
    };
  }, [data]);

  /** pattern plans bucketed by display group, in catalog order */
  const grouped = useMemo(() => {
    const buckets: Record<string, Plan[]> = {};
    for (const plan of patternPlans) {
      const pattern = PATTERN_BY_ID[plan.educationPattern!];
      (buckets[pattern.group] ??= []).push(plan);
    }
    for (const plans of Object.values(buckets)) {
      plans.sort(
        (a, b) =>
          EDUCATION_PATTERNS.findIndex((p) => p.id === a.educationPattern) -
          EDUCATION_PATTERNS.findIndex((p) => p.id === b.educationPattern)
      );
    }
    return buckets;
  }, [patternPlans]);

  function openCreate() {
    setEditing(null);
    setForm(emptyForm);
    setModalOpen(true);
  }

  function openEdit(plan: Plan) {
    setEditing(plan);
    setForm({
      name: plan.name,
      nameBn: plan.nameBn,
      institutionType: plan.institutionType,
      price: String(plan.ratePerStudent ?? plan.price),
      durationMonths: String(plan.durationMonths),
      maxStudents: String(plan.maxStudents),
      features: plan.features.join("\n"),
      featuresBn: plan.featuresBn.join("\n"),
      yearlyDiscountPct: String(planPattern(plan)?.yearlyDiscountPct ?? plan.yearlyDiscountPct ?? ""),
    });
    setModalOpen(true);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      const pattern = editing ? planPattern(editing) : null;
      const payload: Record<string, unknown> = {
        ...form,
        price: Number(form.price),
        durationMonths: Number(form.durationMonths),
        maxStudents: Number(form.maxStudents),
      };
      if (pattern) {
        payload.ratePerStudent = Number(form.price);
        payload.billingBasis = pattern.basis;
        payload.yearlyDiscountPct =
          pattern.yearlyDiscountPct === null
            ? null
            : Math.max(0, Math.min(90, Number(form.yearlyDiscountPct) || 0));
      }
      if (editing) {
        await api(`/api/central/packages/${editing.id}`, { method: "PUT", body: JSON.stringify(payload) });
        setMessage({ type: "success", text: t.central.packages.planUpdated });
      } else {
        await api("/api/central/packages", { method: "POST", body: JSON.stringify(payload) });
        setMessage({ type: "success", text: t.central.packages.planCreated });
      }
      setModalOpen(false);
      reload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setSaving(false);
    }
  }

  async function toggleActive(plan: Plan) {
    try {
      await api(`/api/central/packages/${plan.id}`, {
        method: "PATCH",
        body: JSON.stringify({ isActive: !plan.isActive }),
      });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  async function remove(plan: Plan) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/central/packages/${plan.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: t.common.deletedSuccessfully });
      reload();
    } catch (err) {
      setMessage({
        type: "error",
        text: err instanceof Error && err.message === "IN_USE" ? t.central.packages.cannotDelete : t.common.tryAgain,
      });
    }
  }

  const groupTitle: Record<string, string> = {
    GOVERNMENT: t.central.packages.groupGovernment,
    SCHOOLS: t.central.packages.groupSchools,
    HIGHER: t.central.packages.groupHigher,
    SPECIAL: t.central.packages.groupSpecial,
  };

  return (
    <div>
      <PageHeader
        title={t.central.packages.title}
        subtitle={t.central.packages.subtitle}
        action={
          <Button onClick={openCreate}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{t.central.packages.newPackage}</span>
          </Button>
        }
      />

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

      {/* Hero — pattern intro, setup fee and the live student calculator */}
      <div className="ems-price-hero">
        <div className="ems-price-hero-main">
          <span className="ems-price-hero-badge">{t.central.packages.heroBadge}</span>
          <h3 className="ems-price-hero-title">{t.central.packages.heroTitle}</h3>
          <p className="ems-price-hero-text">{t.central.packages.heroText}</p>
        </div>
        <div className="ems-price-hero-side">
          <div className="ems-price-setup">
            <span className="lbl">{t.central.packages.setupFeeNote}</span>
            <span className="val">{formatBDT(5000, locale)}</span>
            <span className="note">{t.central.packages.setupFeeValue}</span>
          </div>
          <div className="ems-price-calc">
            <label className="k">
              {t.central.packages.studentsLabel}
              <input
                type="number"
                min={1}
                value={calcStudents}
                onChange={(e) => setCalcStudents(Math.max(1, Number(e.target.value) || 1))}
              />
            </label>
            <span className="hint">{t.central.packages.calculatorHint}</span>
          </div>
        </div>
      </div>

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : (
        <>
          {GROUP_ORDER.map((group) =>
            grouped[group]?.length ? (
              <section className="ems-price-group" key={group}>
                <h5 className="ems-price-group-title">
                  <span>{groupTitle[group]}</span>
                </h5>
                <div className="row g-4">
                  {grouped[group].map((plan) => {
                    const pattern = planPattern(plan)!;
                    const monthly = pattern.basis === "PER_STUDENT_MONTH";
                    const perYear = pattern.basis === "PER_STUDENT_YEAR";
                    const estMonthly = estimateCost({
                      pattern,
                      students: calcStudents,
                      cycle: "MONTHLY",
                    });
                    const estYearly = estimateCost({
                      pattern,
                      students: calcStudents,
                      cycle: "YEARLY",
                    });
                    const features = locale === "bn" ? plan.featuresBn : plan.features;
                    return (
                      <div className="col-xxl-3 col-xl-4 col-md-6" key={plan.id}>
                        <div className={`ems-price-card tone-${pattern.tone}${plan.isActive ? "" : " inactive"}`}>
                          <div className="ems-price-top">
                            <span className="ems-price-icon">
                              {pattern.group === "GOVERNMENT" ? (
                                <IconBuilding className="svg-20" />
                              ) : pattern.group === "SPECIAL" ? (
                                <IconSparkle className="svg-20" />
                              ) : (
                                <IconAcademic className="svg-20" />
                              )}
                            </span>
                            <span className={`ems-price-sector sector-${pattern.sector.toLowerCase()}`}>
                              {pattern.sector === "GOVT" ? t.central.packages.govtBadge : groupTitle[group]}
                            </span>
                            <span className={`ems-price-dot${plan.isActive ? "" : " off"}`} />
                          </div>
                          <h5 className="ems-price-name">{locale === "bn" ? plan.nameBn : plan.name}</h5>
                          <div className="ems-price-rate">
                            <span className="amt">{formatBDT(pattern.rate, locale)}</span>
                            <span className="per">
                              {monthly ? t.central.packages.perStudentMonth : t.central.packages.perStudentYear}
                            </span>
                          </div>
                          {monthly && pattern.yearlyDiscountPct ? (
                            <div className="ems-price-yearly">
                              <span className="save">
                                {t.central.packages.saveBadge.replace(
                                  "{pct}",
                                  formatNumber(pattern.yearlyDiscountPct, locale)
                                )}
                              </span>
                              <span className="strike">{formatBDT(estYearly.base, locale)}</span>
                              <span className="now">{formatBDT(estYearly.base - estYearly.discountAmount, locale)}</span>
                              <span className="yr">/ {t.central.packages.yearlyTotal.toLowerCase()}</span>
                            </div>
                          ) : perYear ? (
                            <div className="ems-price-yearly only">
                              <span className="k">{t.central.packages.perStudentYear}</span>
                            </div>
                          ) : null}
                          <ul className="ems-price-features">
                            {features.slice(0, 4).map((f, i) => (
                              <li key={i}>
                                <span className="chk">
                                  <IconCheck className="svg-12" />
                                </span>
                                <span>{f}</span>
                              </li>
                            ))}
                          </ul>
                          <div className="ems-price-est">
                            <span className="k">
                              {formatBDT(calcStudents, locale)} {t.central.packages.studentsWord}:
                            </span>
                            <span className="vals">
                              {perYear ? (
                                <>{formatBDT(estYearly.total, locale)} / {t.central.packages.yearlyTotal.toLowerCase()}</>
                              ) : (
                                <>
                                  {formatBDT(estMonthly.total, locale)} / {t.central.packages.monthlyTotal.toLowerCase()}
                                  {pattern.cycles.includes("YEARLY") && (
                                    <>
                                      {" · "}
                                      {formatBDT(estYearly.total, locale)} / {t.central.packages.yearlyTotal.toLowerCase()}
                                    </>
                                  )}
                                </>
                              )}
                            </span>
                          </div>
                          <div className="ems-price-foot">
                            <span className="subs">
                              {plan._count.subscriptions} × {t.central.packages.subscribers}
                            </span>
                            <div className="actions">
                              <button className="ems-price-act" title={t.common.edit} onClick={() => openEdit(plan)}>
                                <IconEdit className="svg-14" />
                              </button>
                              <button
                                className="ems-price-act"
                                title={plan.isActive ? t.central.packages.deactivate : t.central.packages.activate}
                                onClick={() => toggleActive(plan)}
                              >
                                {plan.isActive ? <IconBan className="svg-14" /> : <IconCheck className="svg-14" />}
                              </button>
                              <button className="ems-price-act danger" title={t.common.delete} onClick={() => remove(plan)}>
                                <IconTrash className="svg-14" />
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </section>
            ) : (
              <Fragment key={group} />
            )
          )}

          {patternPlans.length === 0 && (
            <div className="card">
              <EmptyState icon={<IconPackage />} title={t.common.noData} />
            </div>
          )}

          {/* legacy fixed-price plans — kept for history, hidden from institutions */}
          {legacyPlans.length > 0 && (
            <section className="ems-price-legacy">
              <button className="ems-price-legacy-toggle" onClick={() => setLegacyOpen((v) => !v)}>
                <span>
                  {t.central.packages.legacyNote} ({legacyPlans.length})
                </span>
                <span>{legacyOpen ? "−" : "+"}</span>
              </button>
              {legacyOpen && (
                <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{t.common.package}</th>
                        <th>{t.common.institutionType}</th>
                        <th>{t.common.price}</th>
                        <th>{t.central.packages.monthlyTotal}</th>
                        <th>{t.common.status}</th>
                        <th />
                      </tr>
                    </thead>
                    <tbody>
                      {legacyPlans.map((p) => (
                        <tr key={p.id} className={p.isActive ? "" : "opacity-50"}>
                          <td className="f-w-700">{locale === "bn" ? p.nameBn : p.name}</td>
                          <td className="ems-fs-12 text-muted">
                            {t.types[p.institutionType as keyof typeof t.types]}
                          </td>
                          <td className="f-w-700 ems-text-teal">{formatBDT(p.price, locale)}</td>
                          <td className="ems-fs-12 text-muted">
                            {p.durationMonths} {t.central.packages.monthsShort}
                          </td>
                          <td>
                            <span className={`badge ${p.isActive ? "badge-success" : "badge-secondary"}`}>
                              {p.isActive ? t.common.active : t.common.inactive}
                            </span>
                          </td>
                          <td>
                            <div className="d-flex gap-1 justify-content-end">
                              <button className="ems-price-act" onClick={() => openEdit(p)}>
                                <IconEdit className="svg-14" />
                              </button>
                              <button className="ems-price-act" onClick={() => toggleActive(p)}>
                                {p.isActive ? <IconBan className="svg-14" /> : <IconCheck className="svg-14" />}
                              </button>
                              <button className="ems-price-act danger" onClick={() => remove(p)}>
                                <IconTrash className="svg-14" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </section>
          )}
        </>
      )}

      {/* Create/Edit modal */}
      <Modal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        title={editing ? t.central.packages.editPackage : t.central.packages.newPackage}
        wide
      >
        <form className="theme-form" onSubmit={handleSubmit}>
          {editing?.educationPattern && (
            <div className="ems-price-pattern-strip">
              <span className="k">{t.central.packages.patternLabel}</span>
              <span className="v">
                {locale === "bn" ? editing.nameBn : editing.name}
                {" · "}
                {editing.billingBasis === "PER_STUDENT_YEAR"
                  ? t.central.packages.perStudentYearBasis
                  : t.central.packages.perStudentMonthBasis}
              </span>
            </div>
          )}
          <div className="row">
            <div className="col-md-6">
              <Input
                label={t.central.packages.packageName}
                required
                value={form.name}
                onChange={(e) => setForm({ ...form, name: e.target.value })}
              />
            </div>
            <div className="col-md-6">
              <Input
                label={t.central.packages.packageNameBn}
                value={form.nameBn}
                onChange={(e) => setForm({ ...form, nameBn: e.target.value })}
                placeholder="বাংলা নাম"
              />
            </div>
            {!editing?.educationPattern && (
              <div className="col-md-6">
                <Select
                  label={t.common.institutionType}
                  value={form.institutionType}
                  onChange={(e) => setForm({ ...form, institutionType: e.target.value })}
                >
                  {INSTITUTION_TYPES.map((type) => (
                    <option key={type} value={type}>{t.types[type]}</option>
                  ))}
                </Select>
              </div>
            )}
            <div className="col-md-6">
              <Input
                label={
                  editing?.educationPattern
                    ? t.central.packages.ratePerStudent
                    : t.central.packages.priceBDT
                }
                type="number"
                min="1"
                required
                value={form.price}
                onChange={(e) => setForm({ ...form, price: e.target.value })}
              />
            </div>
            {editing?.educationPattern && planPattern(editing)?.yearlyDiscountPct != null && (
              <div className="col-md-6">
                <Input
                  label={t.central.packages.yearlyDiscount}
                  type="number"
                  min="0"
                  max="90"
                  required
                  value={form.yearlyDiscountPct}
                  onChange={(e) => setForm({ ...form, yearlyDiscountPct: e.target.value })}
                />
              </div>
            )}
            {!editing?.educationPattern && (
              <>
                <div className="col-md-6">
                  <Input
                    label={t.central.packages.durationMonths}
                    type="number"
                    min="1"
                    required
                    value={form.durationMonths}
                    onChange={(e) => setForm({ ...form, durationMonths: e.target.value })}
                  />
                </div>
                <div className="col-md-6">
                  <Input
                    label={t.central.packages.maxStudentsLabel}
                    type="number"
                    min="1"
                    required
                    value={form.maxStudents}
                    onChange={(e) => setForm({ ...form, maxStudents: e.target.value })}
                  />
                </div>
              </>
            )}
            <div className="col-md-6">
              <Textarea
                label={t.central.packages.featuresLabel}
                value={form.features}
                onChange={(e) => setForm({ ...form, features: e.target.value })}
                placeholder={"Feature 1&#10;Feature 2"}
              />
            </div>
            <div className="col-md-6">
              <Textarea
                label={t.central.packages.featuresBnLabel}
                value={form.featuresBn}
                onChange={(e) => setForm({ ...form, featuresBn: e.target.value })}
                placeholder={"ফিচার ১&#10;ফিচার ২"}
              />
            </div>
          </div>
          <div className="d-flex justify-content-end gap-2 pt-2">
            <Button type="button" variant="secondary" onClick={() => setModalOpen(false)}>
              {t.common.cancel}
            </Button>
            <Button type="submit" loading={saving}>
              {editing ? t.common.saveChanges : t.common.create}
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
