"use client";

import { useState } from "react";
import { Badge, Button, Input, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { useSession } from "@/components/session";
import { bpToPct } from "@/components/admin/common";
import { limitText } from "@/components/billing/plan-badge";
import { api, ApiError } from "@/lib/api";
import { formatPaise, paiseToInput, rupeesToPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";
import type { Plan } from "@/lib/types";

function PriceRow({ p, canEdit, onSaved }: { p: Plan; canEdit: boolean; onSaved: () => void }) {
  const toast = useToast();
  const [value, setValue] = useState(paiseToInput(p.price_paise));
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const paise = rupeesToPaise(value);
  const markup = paise !== null ? paise - p.list_price_paise : 0;
  async function save() {
    setBusy(true);
    setError(null);
    try {
      await api.put(`/reseller/plans/${p.id}/price`, { price: value });
      toast("success", `${p.name} price saved`);
      onSaved();
    } catch (e) {
      if (e instanceof ApiError && e.fields.price) setError(e.fields.price);
      else toast("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <tr>
      <td className="px-5 py-3">
        <span className="font-medium">{p.name}</span> {p.custom_price && <Badge tone="teal">Your price</Badge>}
        <p className="text-[13px] text-muted">
          {limitText(p.limits.whatsapp_numbers)} numbers, {limitText(p.limits.team_members)} team, {limitText(p.limits.contacts)} contacts
        </p>
      </td>
      <td className="tabular px-3 py-3 text-right">{formatPaise(p.list_price_paise)}</td>
      <td className="tabular px-3 py-3 text-right text-muted">{formatPaise(p.max_price_paise ?? p.list_price_paise)}</td>
      <td className="px-3 py-3">
        <div className="flex items-center gap-2">
          <Input aria-label={`${p.name} price`} inputMode="decimal" className="w-32" value={value} onChange={(e) => setValue(e.target.value)} disabled={!canEdit} invalid={!!error} />
          {canEdit && (
            <Button size="sm" loading={busy} onClick={save} disabled={paise === p.price_paise}>
              Save
            </Button>
          )}
        </div>
        {error && <p className="mt-1 text-[13px] text-brick">{error}</p>}
      </td>
      <td className="tabular px-5 py-3 text-right">{markup > 0 ? formatPaise(markup) : "—"}</td>
    </tr>
  );
}

export default function ResellerPlansPage() {
  const { can } = useSession();
  const { data, reload } = useApi<{ data: Plan[]; meta: { max_markup_bp: number; commission_rate_bp: number } }>("/reseller/plans");
  return (
    <>
      <PageHeader title="Plan prices" description="What your customers pay per month. You keep the markup above list price, plus your commission on the list price." />
      {!data ? (
        <Skeleton className="h-48" />
      ) : (
        <>
          <p className="mb-4 text-sm text-muted">
            You may charge up to {bpToPct(data.meta.max_markup_bp)} above list. Commission: {bpToPct(data.meta.commission_rate_bp)}. New prices apply to each customer&apos;s next payment.
          </p>
          <Panel>
            <div className="relative overflow-x-auto">
              <table className="w-full min-w-[760px] text-sm">
                <thead className="border-b border-line text-left text-[13px] text-muted">
                  <tr>
                    <th className="px-5 py-3 font-medium">Plan</th>
                    <th className="px-3 py-3 text-right font-medium">List price</th>
                    <th className="px-3 py-3 text-right font-medium">Highest allowed</th>
                    <th className="px-3 py-3 font-medium">Your price (₹)</th>
                    <th className="px-5 py-3 text-right font-medium">Your markup</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-line">
                  {data.data.map((p) => (
                    <PriceRow key={`${p.id}-${p.price_paise}`} p={p} canEdit={can("reseller.manage")} onSaved={reload} />
                  ))}
                </tbody>
              </table>
            </div>
          </Panel>
        </>
      )}
    </>
  );
}
