"use client";

import { useEffect, useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Select,
  StatusBadge,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatBDT, formatNumber } from "@/lib/utils";
import { PRICING_CATEGORY_BY_CODE, PRICING_CATEGORIES, yearlyEffectiveMonthly } from "@/lib/pricing";
import { IconCard, IconPlus, IconSparkle } from "@/components/icons";
import { emsConfirm } from "@/components/ConfirmDialog";

interface Tier {
  id: number;
  category: string;
  minStudents: number;
  maxStudents: number | null;
  monthlyPrice: string;
  yearlyDiscount: string;
  active: boolean;
  sortOrder: number;
}

const emptyForm = { category: "GOVT_SCHOOL", minStudents: "0", maxStudents: "", monthlyPrice: "", yearlyDiscount: "0", active: true };

export default function CentralPricingPage() {
  const { t, locale } = useLang();
  const p = t.central.pricingPage;
  const { data, loading, reload } = useApi<{ tiers: Tier[] }>("/api/central/pricing-tiers");
  const { data: referralData, reload: referralReload } = useApi<{ discountPct: number }>(
    "/api/central/settings/referral"
  );
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // referral program: the discount institutions registering with a
  // subscriber's referral code get on their first package purchase
  const [referralPct, setReferralPct] = useState("");
  const [referralSaving, setReferralSaving] = useState(false);
  const [referralLoaded, setReferralLoaded] = useState<number | null>(null);
  useEffect(() => {
    if (referralData && referralLoaded === null) {
      setReferralPct(String(referralData.discountPct));
      setReferralLoaded(referralData.discountPct);
    }
  }, [referralData, referralLoaded]);

  /** Save the referral discount percentage (0 turns the benefit off). */
  async function saveReferralPct() {
    const n = Number(referralPct);
    if (!Number.isFinite(n) || n < 0 || n > 90) {
      setMessage({ type: "error", text: t.central.packages.referralInvalid });
      return;
    }
    setReferralSaving(true);
    try {
      const res = await api<{ discountPct: number }>("/api/central/settings/referral", {
        method: "PUT",
        body: JSON.stringify({ discountPct: n }),
      });
      setMessage({
        type: "success",
        text: t.central.packages.referralSaved.replace("{pct}", String(res.discountPct)),
      });
      setReferralPct(String(res.discountPct));
      setReferralLoaded(res.discountPct);
      referralReload();
    } catch (err) {
      setMessage({ type: "error", text: err instanceof Error ? err.message : t.common.tryAgain });
    } finally {
      setReferralSaving(false);
    }
  }

  // add/edit modal
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<Tier | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [busyId, setBusyId] = useState<number | null>(null);

  const tiers = data?.tiers ?? [];

  const byCategory = useMemo(() => {
    const map = new Map<string, Tier[]>();
    for (const tier of tiers) {
      const list = map.get(tier.category) ?? [];
      list.push(tier);
      map.set(tier.category, list);
    }
    for (const list of map.values()) list.sort((a, b) => a.minStudents - b.minStudents);
    return map;
  }, [tiers]);

  function openAdd(category?: string) {
    setEditing(null);
    setForm({ ...emptyForm, category: category ?? form.category });
    setModalOpen(true);
  }

  function openEdit(tier: Tier) {
    setEditing(tier);
    setForm({
      category: tier.category,
      minStudents: String(tier.minStudents),
      maxStudents: tier.maxStudents === null ? "" : String(tier.maxStudents),
      monthlyPrice: String(Number(tier.monthlyPrice)),
      yearlyDiscount: String(Number(tier.yearlyDiscount)),
      active: tier.active,
    });
    setModalOpen(true);
  }

  function errText(code: string) {
    if (code === "INVALID_RANGE") return p.invalidRange;
    if (code === "INVALID_PRICE") return p.invalidPrice;
    if (code === "INVALID_DISCOUNT") return p.invalidDiscount;
    return t.common.tryAgain;
  }

  async function save() {
    setSaving(true);
    setMessage(null);
    try {
      if (editing) {
        await api(`/api/central/pricing-tiers/${editing.id}`, {
          method: "PATCH",
          body: JSON.stringify({
            minStudents: form.minStudents,
            maxStudents: form.maxStudents,
            monthlyPrice: form.monthlyPrice,
            yearlyDiscount: form.yearlyDiscount,
            active: form.active,
          }),
        });
      } else {
        await api("/api/central/pricing-tiers", {
          method: "POST",
          body: JSON.stringify(form),
        });
      }
      setModalOpen(false);
      setMessage({ type: "success", text: p.tierSaved });
      reload();
    } catch (err) {
      setMessage({ type: "error", text: errText(err instanceof Error ? err.message : "") });
    } finally {
      setSaving(false);
    }
  }

  async function toggleActive(tier: Tier) {
    setBusyId(tier.id);
    try {
      await api(`/api/central/pricing-tiers/${tier.id}`, {
        method: "PATCH",
        body: JSON.stringify({ active: !tier.active }),
      });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  async function remove(tier: Tier) {
    if (!(await emsConfirm({ message: p.deleteConfirm, danger: true }))) return;
    setBusyId(tier.id);
    try {
      await api(`/api/central/pricing-tiers/${tier.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: p.tierDeleted });
      reload();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setBusyId(null);
    }
  }

  const canSave =
    form.minStudents !== "" &&
    form.monthlyPrice !== "" &&
    Number(form.monthlyPrice) > 0 &&
    (form.maxStudents === "" || Number(form.maxStudents) > Number(form.minStudents)) &&
    Number(form.yearlyDiscount) >= 0 &&
    Number(form.yearlyDiscount) <= 90;

  return (
    <div>
      <PageHeader
        title={p.title}
        subtitle={p.subtitle}
        action={
          <Button onClick={() => openAdd()}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{p.addTier}</span>
          </Button>
        }
      />

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

      {/* Referral program — every subscriber holds a code; referred institutions
          get this percentage off their first package purchase */}
      <div className="card p-3 mb-4">
        <div className="d-flex flex-wrap align-items-center gap-2">
          <span className="f-w-800 ems-fs-13" style={{ color: "#24695c" }}>
            <IconSparkle className="svg-16" /> {t.central.packages.referralTitle}
          </span>
          <div className="d-flex align-items-center gap-2">
            <input
              type="number"
              min={0}
              max={90}
              className="form-control form-control-sm"
              style={{ maxWidth: 90 }}
              value={referralPct}
              onChange={(e) => setReferralPct(e.target.value)}
            />
            <span className="f-w-700">%</span>
          </div>
          <Button size="sm" variant="primary" loading={referralSaving} onClick={saveReferralPct}>
            {t.common.save}
          </Button>
          <span className="ems-fs-12 text-muted">{t.central.packages.referralHint}</span>
        </div>
      </div>

      <p className="ems-fs-12 text-muted mb-3">
        <IconCard className="svg-14 me-1" />
        {p.previewHint}
      </p>

      {loading ? (
        <PageLoader text={t.common.loading} />
      ) : (
        <div className="row g-4">
          {PRICING_CATEGORIES.map((cat) => {
            const catTiers = byCategory.get(cat.code) ?? [];
            return (
              <div className="col-md-6 col-xl-4" key={cat.code}>
                <div className={`card h-100 ${catTiers.length === 0 ? "opacity-75" : ""}`}>
                  <div className="card-header d-flex align-items-center justify-content-between">
                    <div>
                      <h6 className="mb-0 f-w-700">{locale === "bn" ? cat.nameBn : cat.name}</h6>
                      <span className={`ems-type-pill ems-type-${cat.types[0]} mt-1 d-inline-block`}>
                        {t.types[cat.types[0] as keyof typeof t.types]}
                        {cat.types.length > 1 ? ` +${cat.types.length - 1}` : ""}
                      </span>
                    </div>
                    <Button size="sm" variant="secondary" onClick={() => openAdd(cat.code)}>
                      <IconPlus className="svg-14" />
                      <span className="ms-1 d-none d-lg-inline">{p.addTier}</span>
                    </Button>
                  </div>
                  <div className="card-body">
                    {catTiers.length === 0 ? (
                      <EmptyState title={p.noTiers} />
                    ) : (
                      <div className="d-flex flex-column gap-2">
                        {catTiers.map((tier) => {
                          const monthly = Number(tier.monthlyPrice);
                          const discount = Number(tier.yearlyDiscount);
                          const eff = yearlyEffectiveMonthly(monthly, discount);
                          return (
                            <div key={tier.id} className="border rounded-3 px-3 py-2">
                              <div className="d-flex align-items-center justify-content-between gap-2">
                                <div>
                                  <span className="badge badge-soft-teal">
                                    {formatNumber(tier.minStudents, locale)}
                                    {tier.maxStudents ? `–${formatNumber(tier.maxStudents, locale)}` : "+"}{" "}
                                    {t.common.students}
                                  </span>
                                  <span className="f-w-800 ms-2">{formatBDT(monthly, locale)}</span>
                                  <span className="ems-fs-11 text-muted">{t.landing.perMonth}</span>
                                </div>
                                <StatusBadge
                                  status={tier.active ? "ACTIVE" : "SUSPENDED"}
                                  label={tier.active ? t.common.active : t.common.inactive}
                                />
                              </div>
                              {discount > 0 && (
                                <p className="mb-0 mt-1 ems-fs-11">
                                  <span className="text-success f-w-700">
                                    {t.landing.yearlySave.replace("{pct}", formatNumber(discount, locale))}
                                  </span>
                                  <span className="text-muted ms-2">
                                    = {formatBDT(eff, locale)} {t.landing.perMonth}
                                  </span>
                                </p>
                              )}
                              <div className="d-flex justify-content-end gap-1 mt-2">
                                <Button size="sm" variant="secondary" loading={busyId === tier.id} onClick={() => toggleActive(tier)}>
                                  {tier.active ? t.common.inactive : t.common.active}
                                </Button>
                                <Button size="sm" variant="outline" onClick={() => openEdit(tier)}>
                                  {t.common.edit}
                                </Button>
                                <Button size="sm" variant="danger" loading={busyId === tier.id} onClick={() => remove(tier)}>
                                  {t.common.delete}
                                </Button>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Add / edit tier modal */}
      <Modal open={modalOpen} onClose={() => setModalOpen(false)} title={editing ? p.editTier : p.addTier}>
        <Select
          label={p.category}
          value={form.category}
          disabled={!!editing}
          onChange={(e) => setForm({ ...form, category: e.target.value })}
        >
          {PRICING_CATEGORIES.map((c) => (
            <option key={c.code} value={c.code}>
              {locale === "bn" ? c.nameBn : c.name}
            </option>
          ))}
        </Select>
        <div className="row">
          <div className="col-6">
            <Input
              label={p.minStudents}
              type="number"
              min={0}
              value={form.minStudents}
              onChange={(e) => setForm({ ...form, minStudents: e.target.value })}
            />
          </div>
          <div className="col-6">
            <Input
              label={p.maxStudents}
              type="number"
              min={0}
              placeholder="300"
              value={form.maxStudents}
              onChange={(e) => setForm({ ...form, maxStudents: e.target.value })}
            />
          </div>
          <p className="ems-fs-11 text-muted mb-2">{p.maxUnlimited}</p>
          <div className="col-6">
            <Input
              label={p.monthlyPrice}
              type="number"
              min={0}
              value={form.monthlyPrice}
              placeholder="2000"
              onChange={(e) => setForm({ ...form, monthlyPrice: e.target.value })}
            />
          </div>
          <div className="col-6">
            <Input
              label={p.yearlyDiscount}
              type="number"
              min={0}
              max={90}
              value={form.yearlyDiscount}
              onChange={(e) => setForm({ ...form, yearlyDiscount: e.target.value })}
            />
          </div>
          <p className="ems-fs-11 text-muted mb-2">{p.yearlyHint}</p>
        </div>
        <div className="form-check form-switch mb-3">
          <input
            className="form-check-input"
            type="checkbox"
            role="switch"
            id="tier-active"
            checked={form.active}
            onChange={(e) => setForm({ ...form, active: e.target.checked })}
          />
          <label className="form-check-label ems-fs-12 f-w-600" htmlFor="tier-active">
            {t.common.active}
          </label>
        </div>
        <div className="d-flex justify-content-end gap-2">
          <Button variant="secondary" onClick={() => setModalOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button onClick={save} loading={saving} disabled={!canSave}>
            {t.common.save}
          </Button>
        </div>
      </Modal>
    </div>
  );
}
