"use client";

import { useState } from "react";
import { Pencil, Plus, Tags, Trash2 } from "lucide-react";
import { Badge, Button, ConfirmDialog, Dialog, EmptyState, Field, Input, PageHeader, Panel, Select, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { useSession } from "@/components/session";
import { api, ApiError } from "@/lib/api";
import { formatPaise, paiseToInput } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Rule {
  id: number;
  category: "marketing" | "utility" | "authentication";
  country_prefix: string;
  price_paise: number;
  provider_cost_micro: number;
  margin_paise_approx: number;
  is_active: boolean;
}
const microToRupees = (m: number) => `${Math.floor(m / 1_000_000)}.${String(m % 1_000_000).padStart(6, "0")}`.replace(/0+$/, "").replace(/\.$/, "");

function RuleDialog({ rule, onClose, onDone }: { rule?: Rule; onClose: () => void; onDone: () => void }) {
  const toast = useToast();
  const [f, setF] = useState({ category: rule?.category ?? "marketing", country_prefix: rule?.country_prefix ?? "91", price: rule ? paiseToInput(rule.price_paise) : "", provider_cost: rule ? microToRupees(rule.provider_cost_micro) : "", is_active: rule?.is_active ?? true });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  async function save() {
    setBusy(true);
    setErrors({});
    try {
      await api.put("/admin/pricing-rules", f);
      toast("success", "Price saved");
      onDone();
    } catch (e) {
      if (e instanceof ApiError && Object.keys(e.fields).length) setErrors(e.fields);
      else toast("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <Dialog
      open
      onClose={onClose}
      title={rule ? "Edit message price" : "New message price"}
      description="What customers pay per delivered template message, and Meta's rate for the same message (for margin reporting)."
      footer={
        <>
          <Button onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={busy} onClick={save}>
            Save
          </Button>
        </>
      }
    >
      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Category" htmlFor="pr-cat">
          <Select id="pr-cat" value={f.category} onChange={(e) => setF({ ...f, category: e.target.value as Rule["category"] })} disabled={!!rule}>
            <option value="marketing">Marketing</option>
            <option value="utility">Utility</option>
            <option value="authentication">Authentication</option>
          </Select>
        </Field>
        <Field label="Recipient calling code" htmlFor="pr-prefix" error={errors.country_prefix} hint="91 for India; * for all others">
          <Input id="pr-prefix" value={f.country_prefix} onChange={(e) => setF({ ...f, country_prefix: e.target.value })} disabled={!!rule} invalid={!!errors.country_prefix} />
        </Field>
        <Field label="Customer price (₹)" htmlFor="pr-price" error={errors.price}>
          <Input id="pr-price" inputMode="decimal" value={f.price} onChange={(e) => setF({ ...f, price: e.target.value })} invalid={!!errors.price} />
        </Field>
        <Field label="Meta's rate (₹)" htmlFor="pr-cost" error={errors.provider_cost} hint="Up to 6 decimals, from Meta's rate card">
          <Input id="pr-cost" inputMode="decimal" value={f.provider_cost} onChange={(e) => setF({ ...f, provider_cost: e.target.value })} invalid={!!errors.provider_cost} />
        </Field>
        <label className="flex items-center gap-2 text-sm sm:col-span-2">
          <input type="checkbox" className="size-4 accent-teal" checked={f.is_active} onChange={(e) => setF({ ...f, is_active: e.target.checked })} />
          Active
        </label>
      </div>
    </Dialog>
  );
}

export default function AdminPricingPage() {
  const toast = useToast();
  const { can } = useSession();
  const manage = can("platform.billing.manage");
  const { data, reload } = useApi<{ data: Rule[] }>("/admin/pricing-rules");
  const [editing, setEditing] = useState<Rule | "new" | null>(null);
  const [deleting, setDeleting] = useState<Rule | null>(null);
  async function remove() {
    if (!deleting) return;
    try {
      await api.delete(`/admin/pricing-rules/${deleting.id}`);
      toast("success", "Price removed");
      setDeleting(null);
      reload();
    } catch (e) {
      toast("error", (e as Error).message);
    }
  }
  return (
    <>
      <PageHeader
        title="Message pricing"
        description="WhatsApp charges per delivered template message by category and recipient country. These prices are what your customers' wallets pay."
        actions={
          manage && (
            <Button variant="primary" icon={<Plus className="size-4" />} onClick={() => setEditing("new")}>
              New price
            </Button>
          )
        }
      />
      <p className="mb-4 max-w-3xl rounded-lg bg-white px-4 py-3 text-[13px] text-muted ring-1 ring-line">
        Check Meta&apos;s current rate card before changing prices: rates change by country and over time, and India-billed accounts move to INR rates during 2026. A calling code matches the longest prefix; * covers every
        other country. Service replies and utility templates inside the 24-hour window are free and never charged.
      </p>
      <Panel>
        {!data ? (
          <Skeleton className="m-5 h-32" />
        ) : data.data.length === 0 ? (
          <EmptyState icon={<Tags />} title="No message prices" body="Without prices, template messages are not charged to customer wallets." />
        ) : (
          <div className="relative overflow-x-auto">
            <table className="w-full min-w-[640px] text-sm">
              <thead className="border-b border-line text-left text-[13px] text-muted">
                <tr>
                  <th className="px-5 py-3 font-medium">Category</th>
                  <th className="px-3 py-3 font-medium">Recipients</th>
                  <th className="px-3 py-3 text-right font-medium">Customer price</th>
                  <th className="px-3 py-3 text-right font-medium">Meta&apos;s rate</th>
                  <th className="px-3 py-3 text-right font-medium">Margin</th>
                  <th className="px-5 py-3 text-right font-medium">
                    <span className="sr-only">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line">
                {data.data.map((r) => (
                  <tr key={r.id} className={r.is_active ? "" : "text-muted"}>
                    <td className="px-5 py-3 capitalize">
                      {r.category} {!r.is_active && <Badge>Off</Badge>}
                    </td>
                    <td className="px-3 py-3">{r.country_prefix === "*" ? "All other countries" : `+${r.country_prefix}`}</td>
                    <td className="tabular px-3 py-3 text-right">{formatPaise(r.price_paise)}</td>
                    <td className="tabular px-3 py-3 text-right text-muted">₹{microToRupees(r.provider_cost_micro)}</td>
                    <td className={`tabular px-3 py-3 text-right ${r.margin_paise_approx < 0 ? "text-brick" : ""}`}>{formatPaise(r.margin_paise_approx)}</td>
                    <td className="px-5 py-3">
                      {manage && (
                        <div className="flex justify-end gap-1">
                          <button onClick={() => setEditing(r)} className="rounded p-1.5 text-muted hover:bg-paper hover:text-teal" aria-label={`Edit ${r.category} ${r.country_prefix}`}>
                            <Pencil className="size-4" />
                          </button>
                          <button onClick={() => setDeleting(r)} className="rounded p-1.5 text-muted hover:bg-paper hover:text-brick" aria-label={`Delete ${r.category} ${r.country_prefix}`}>
                            <Trash2 className="size-4" />
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>
      {editing && <RuleDialog rule={editing === "new" ? undefined : editing} onClose={() => setEditing(null)} onDone={() => (setEditing(null), reload())} />}
      <ConfirmDialog open={!!deleting} title="Remove this price?" message="Messages it covered fall back to the * price for the category, or are not charged if there is none." confirmLabel="Remove" onConfirm={remove} onClose={() => setDeleting(null)} />
    </>
  );
}
