"use client";

import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
import { ArrowLeft } from "lucide-react";
import { Badge, Button, ConfirmDialog, Dialog, Field, Panel, Select, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { useSession } from "@/components/session";
import { PAYMENT_STATUS, SubscriptionBadge } from "@/components/billing/plan-badge";
import { api } from "@/lib/api";
import { formatDate, formatDateTime, formatPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";
import type { CustomerRow, Payment, Plan } from "@/lib/types";
import { StatTile } from "./common";

type Detail = CustomerRow & { payments: Payment[]; usage_30d: { messages: number; charged_paise: number }; earnings_from_customer_paise: number };

export function ResellerCustomerDetail() {
  const { id } = useParams<{ id: string }>();
  const toast = useToast();
  const { can } = useSession();
  const { data, error, reload } = useApi<{ data: Detail }>(`/reseller/customers/${id}`);
  const plans = useApi<{ data: Plan[] }>("/reseller/plans");
  const [dialog, setDialog] = useState<"plan" | "status" | null>(null);
  const [planId, setPlanId] = useState("");
  const [busy, setBusy] = useState(false);
  const c = data?.data;
  const manage = can("reseller.manage");

  async function run(fn: () => Promise<unknown>, ok: string) {
    setBusy(true);
    try {
      await fn();
      toast("success", ok);
      setDialog(null);
      reload();
    } catch (e) {
      toast("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  }

  if (error) return <p className="rounded-md bg-brick-soft px-4 py-3 text-sm text-brick">{error}</p>;
  if (!c) return <Skeleton className="h-96" />;
  return (
    <>
      <Link href="/reseller/customers" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-teal">
        <ArrowLeft className="size-4" /> Customers
      </Link>
      <header className="mb-6 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
        <div>
          <h1 className="flex flex-wrap items-center gap-3 text-2xl font-semibold tracking-tight text-ink">
            {c.name} <Badge tone={c.status === "active" ? "teal" : "brick"}>{c.status === "active" ? "Active" : "Suspended"}</Badge>
          </h1>
          <p className="mt-1 text-sm text-muted">{c.owner ? `${c.owner.name}, ${c.owner.email}` : ""}</p>
        </div>
        {manage && (
          <div className="flex flex-wrap gap-2">
            <Button onClick={() => (setPlanId(String(c.subscription?.plan.id ?? plans.data?.data[0]?.id ?? "")), setDialog("plan"))}>Change plan</Button>
            <Button variant={c.status === "active" ? "danger" : "primary"} onClick={() => setDialog("status")}>
              {c.status === "active" ? "Suspend" : "Reactivate"}
            </Button>
          </div>
        )}
      </header>
      <div className="mb-6 grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatTile label="Plan" value={c.subscription?.plan.name ?? "Not billed"} sub={c.subscription ? <SubscriptionBadge status={c.subscription.status} /> : undefined} />
        <StatTile label="Renews or ends" value={c.subscription ? formatDate(c.subscription.current_period_end) : "—"} />
        <StatTile label="Messages, 30 days" value={c.usage_30d.messages.toLocaleString("en-IN")} sub={`${formatPaise(c.usage_30d.charged_paise)} charged`} />
        <StatTile label="You earned from them" value={formatPaise(c.earnings_from_customer_paise)} />
      </div>
      <Panel>
        <h2 className="border-b border-line px-5 py-3 font-semibold">Payments</h2>
        {c.payments.length === 0 ? (
          <p className="px-5 py-8 text-center text-sm text-muted">No payments yet.</p>
        ) : (
          <ul className="divide-y divide-line">
            {c.payments.map((p) => (
              <li key={p.id} className="flex items-center gap-3 px-5 py-3 text-sm">
                <div className="min-w-0 flex-1">
                  <p className="font-medium">
                    {p.purpose === "recharge" ? "Wallet recharge" : "Plan"} <span className="tabular">{formatPaise(p.total_paise)}</span>
                  </p>
                  <p className="text-[13px] text-muted">{formatDateTime(p.paid_at ?? p.created_at)}</p>
                </div>
                <Badge tone={PAYMENT_STATUS[p.status]?.tone ?? "neutral"}>{PAYMENT_STATUS[p.status]?.label ?? p.status}</Badge>
              </li>
            ))}
          </ul>
        )}
      </Panel>
      {dialog === "plan" && plans.data && (
        <Dialog
          open
          onClose={() => setDialog(null)}
          title="Change plan"
          description="The customer moves to the new plan now; your price for it applies from their next payment."
          footer={
            <>
              <Button onClick={() => setDialog(null)}>Cancel</Button>
              <Button variant="primary" loading={busy} onClick={() => run(() => api.post(`/reseller/customers/${c.id}/plan`, { plan_id: Number(planId) }), "Plan changed")}>
                Change plan
              </Button>
            </>
          }
        >
          <Field label="Plan" htmlFor="rc-plan">
            <Select id="rc-plan" value={planId} onChange={(e) => setPlanId(e.target.value)}>
              {plans.data.data.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.name}, {formatPaise(p.price_paise, { compact: true })}/{p.interval}
                </option>
              ))}
            </Select>
          </Field>
        </Dialog>
      )}
      <ConfirmDialog
        open={dialog === "status"}
        title={c.status === "active" ? `Suspend ${c.name}?` : `Reactivate ${c.name}?`}
        message={c.status === "active" ? "Their team can't use Devwebs until you reactivate the workspace. Data is kept." : "Their team can use Devwebs again straight away."}
        confirmLabel={c.status === "active" ? "Suspend" : "Reactivate"}
        loading={busy}
        onConfirm={() => run(() => api.post(`/reseller/customers/${c.id}/status`, { status: c.status === "active" ? "suspended" : "active" }), c.status === "active" ? "Customer suspended" : "Customer reactivated")}
        onClose={() => setDialog(null)}
      />
    </>
  );
}
