"use client";

import { useState, type FormEvent } from "react";
import { Copy } from "lucide-react";
import { Badge, Button, Field, Input, PageHeader, Panel, Skeleton } from "@/components/ui/kit";
import { useToast } from "@/components/ui/toast";
import { api, ApiError } from "@/lib/api";
import { paiseToInput, rupeesToPaise } from "@/lib/format";
import { useApi } from "@/lib/use-api";

interface Settings {
  tax_rate_bp: string;
  tax_label: string;
  seller_name: string;
  seller_gstin: string;
  seller_address: string;
  seller_state_code: string;
  invoice_prefix: string;
  grace_days: string;
  low_balance_default_paise: string;
  min_recharge_paise: string;
  max_recharge_paise: string;
  razorpay_key_id: string;
  razorpay_key_secret: boolean;
  razorpay_webhook_secret: boolean;
  payments_mode: "razorpay" | "simulation";
  webhook_url: string;
}

function SettingsForm({ s, onSaved }: { s: Settings; onSaved: () => void }) {
  const toast = useToast();
  const [f, setF] = useState({
    tax_rate: String(Number(s.tax_rate_bp) / 100),
    seller_name: s.seller_name,
    seller_gstin: s.seller_gstin,
    seller_address: s.seller_address,
    seller_state_code: s.seller_state_code,
    invoice_prefix: s.invoice_prefix,
    grace_days: s.grace_days,
    low: paiseToInput(Number(s.low_balance_default_paise)),
    min: paiseToInput(Number(s.min_recharge_paise)),
    max: paiseToInput(Number(s.max_recharge_paise)),
    razorpay_key_id: s.razorpay_key_id,
    razorpay_key_secret: "",
    razorpay_webhook_secret: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);
  const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: e.target.value });
  async function save(e: FormEvent) {
    e.preventDefault();
    setBusy(true);
    setErrors({});
    try {
      await api.put("/admin/settings", {
        tax_rate_bp: Math.round(Number(f.tax_rate) * 100),
        seller_name: f.seller_name,
        seller_gstin: f.seller_gstin,
        seller_address: f.seller_address,
        seller_state_code: f.seller_state_code,
        invoice_prefix: f.invoice_prefix,
        grace_days: Number(f.grace_days),
        low_balance_default_paise: rupeesToPaise(f.low) ?? 0,
        min_recharge_paise: rupeesToPaise(f.min) ?? 100,
        max_recharge_paise: rupeesToPaise(f.max) ?? 100,
        razorpay_key_id: f.razorpay_key_id,
        razorpay_key_secret: f.razorpay_key_secret,
        razorpay_webhook_secret: f.razorpay_webhook_secret,
      });
      toast("success", "Settings saved");
      onSaved();
    } catch (err) {
      if (err instanceof ApiError && Object.keys(err.fields).length) setErrors(err.fields);
      else toast("error", (err as Error).message);
    } finally {
      setBusy(false);
    }
  }
  return (
    <form onSubmit={save} className="space-y-6">
      <Panel className="p-5">
        <h2 className="mb-4 font-semibold">Razorpay</h2>
        <div className="mb-4 flex flex-wrap items-center gap-2 text-sm">
          Mode: {s.payments_mode === "razorpay" ? <Badge tone="teal">Live API</Badge> : <Badge tone="amber">Test simulation (PAYMENTS_PROVIDER=fake)</Badge>}
        </div>
        <div className="grid gap-4 md:grid-cols-3">
          <Field label="Key id" htmlFor="st-kid" error={errors.razorpay_key_id}>
            <Input id="st-kid" value={f.razorpay_key_id} onChange={set("razorpay_key_id")} placeholder="rzp_live_…" invalid={!!errors.razorpay_key_id} />
          </Field>
          <Field label="Key secret" htmlFor="st-ksec" hint={s.razorpay_key_secret ? "Saved. Leave empty to keep it." : "Not set"}>
            <Input id="st-ksec" type="password" autoComplete="off" value={f.razorpay_key_secret} onChange={set("razorpay_key_secret")} />
          </Field>
          <Field label="Webhook secret" htmlFor="st-wsec" hint={s.razorpay_webhook_secret ? "Saved. Leave empty to keep it." : "Not set"}>
            <Input id="st-wsec" type="password" autoComplete="off" value={f.razorpay_webhook_secret} onChange={set("razorpay_webhook_secret")} />
          </Field>
        </div>
        <div className="mt-4 rounded-lg bg-paper p-3 text-[13px]">
          <p className="font-medium">Webhook URL for the Razorpay Dashboard</p>
          <p className="mt-1 flex items-center gap-2 break-all font-mono text-[12px]">
            {s.webhook_url}
            <button type="button" className="shrink-0 rounded p-1 text-muted hover:bg-white hover:text-teal" aria-label="Copy webhook URL" onClick={() => navigator.clipboard.writeText(s.webhook_url).then(() => toast("success", "Copied"))}>
              <Copy className="size-3.5" />
            </button>
          </p>
          <p className="mt-1 text-muted">Subscribe to payment.captured, payment.failed, order.paid, refund.processed and refund.failed. Turn on automatic capture.</p>
        </div>
        <p className="mt-3 text-[13px] text-muted">Secrets are encrypted at rest and never shown again. Environment variables RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET and RAZORPAY_WEBHOOK_SECRET are used when these are empty.</p>
      </Panel>

      <Panel className="p-5">
        <h2 className="mb-4 font-semibold">Invoices and tax</h2>
        <div className="grid gap-4 md:grid-cols-3">
          <Field label="Seller name" htmlFor="st-sname" error={errors.seller_name}>
            <Input id="st-sname" value={f.seller_name} onChange={set("seller_name")} />
          </Field>
          <Field label="Seller GSTIN" htmlFor="st-gstin" error={errors.seller_gstin}>
            <Input id="st-gstin" value={f.seller_gstin} onChange={set("seller_gstin")} maxLength={15} invalid={!!errors.seller_gstin} />
          </Field>
          <Field label="Seller state code" htmlFor="st-state" error={errors.seller_state_code} hint="Same state as the buyer → CGST + SGST; otherwise IGST">
            <Input id="st-state" value={f.seller_state_code} onChange={set("seller_state_code")} maxLength={2} invalid={!!errors.seller_state_code} />
          </Field>
          <div className="md:col-span-2">
            <Field label="Seller address" htmlFor="st-addr">
              <Input id="st-addr" value={f.seller_address} onChange={set("seller_address")} />
            </Field>
          </div>
          <Field label="GST rate (%)" htmlFor="st-tax" error={errors.tax_rate_bp}>
            <Input id="st-tax" inputMode="decimal" value={f.tax_rate} onChange={set("tax_rate")} />
          </Field>
          <Field label="Invoice prefix" htmlFor="st-prefix" error={errors.invoice_prefix} hint="Numbers run per financial year, e.g. DW/2026-27/00001">
            <Input id="st-prefix" value={f.invoice_prefix} onChange={set("invoice_prefix")} invalid={!!errors.invoice_prefix} />
          </Field>
        </div>
      </Panel>

      <Panel className="p-5">
        <h2 className="mb-4 font-semibold">Wallet and subscriptions</h2>
        <div className="grid gap-4 md:grid-cols-4">
          <Field label="Minimum recharge (₹)" htmlFor="st-min">
            <Input id="st-min" inputMode="decimal" value={f.min} onChange={set("min")} />
          </Field>
          <Field label="Maximum recharge (₹)" htmlFor="st-max">
            <Input id="st-max" inputMode="decimal" value={f.max} onChange={set("max")} />
          </Field>
          <Field label="Default low-balance alert (₹)" htmlFor="st-low">
            <Input id="st-low" inputMode="decimal" value={f.low} onChange={set("low")} />
          </Field>
          <Field label="Grace days before suspension" htmlFor="st-grace" error={errors.grace_days}>
            <Input id="st-grace" inputMode="numeric" value={f.grace_days} onChange={set("grace_days")} />
          </Field>
        </div>
      </Panel>
      <Button type="submit" variant="primary" loading={busy}>
        Save settings
      </Button>
    </form>
  );
}

export default function AdminSettingsPage() {
  const { data, reload } = useApi<{ data: Settings }>("/admin/settings");
  const [v, setV] = useState(0);
  return (
    <>
      <PageHeader title="Billing settings" description="Payment gateway keys, invoice details, tax and wallet rules for the whole platform." />
      {!data ? (
        <Skeleton className="h-96" />
      ) : (
        <SettingsForm
          key={v}
          s={data.data}
          onSaved={() => {
            reload();
            setV((x) => x + 1);
          }}
        />
      )}
    </>
  );
}
