"use client";

import { useCallback, useEffect, useState } from "react";
import { Wallet, IndianRupee, BadgeCheck, Download, Send, Gift, Copy } from "lucide-react";
import { api, auth } from "@/lib/api";
import { PageHeader, StatCard, Card, Button, Input, FormField, Badge, Skeleton, EmptyState } from "@/components/ui";
import { cn } from "@/components/cn";
import { useToast } from "@/components/toast";
import { useConfirm } from "@/components/modal";

type Payout = { id: string; amount: number; status: string; method: string; reference: string | null; date: string };
type Data = {
  balance: number;
  minPayout: number;
  payoutMethods: string[];
  paymentMethod: string | null;
  paymentDetails: { info?: string } | null;
  stats: { earnings: number };
  orders: { orderId: string; date: string; total: number; commission: number; status: string }[];
  payouts: Payout[];
};

const inr = (n: number) => "₹" + Math.round(n).toLocaleString("en-IN");

export default function PaymentsPage() {
  const toast = useToast();
  const confirm = useConfirm();
  const [d, setD] = useState<Data | null>(null);
  const [method, setMethod] = useState<"STORE_CREDIT" | "PAYPAL">("STORE_CREDIT");
  const [paypal, setPaypal] = useState("");
  const [savingPay, setSavingPay] = useState(false);

  const load = useCallback(async () => {
    const id = auth.get()?.id;
    if (!id) return;
    const data: Data = await api.get(`/affiliates/${id}`);
    setD(data);
    const supported = data.payoutMethods || [];
    const current = data.paymentMethod && supported.includes(data.paymentMethod) ? data.paymentMethod : supported.includes("STORE_CREDIT") ? "STORE_CREDIT" : "PAYPAL";
    setMethod(current === "PAYPAL" ? "PAYPAL" : "STORE_CREDIT");
    setPaypal(data.paymentDetails?.info ?? "");
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  const requestPayout = async () => {
    const id = auth.get()?.id;
    if (!id || !d) return;
    if (!(await confirm({ title: "Request payout?", message: `Request a payout of ${inr(d.balance)}. The brand will process it via your chosen method.`, confirmText: "Request" }))) return;
    try {
      const r = await api.post(`/affiliates/${id}/payout-request`);
      toast.success(`Payout of ${inr(r.requested)} requested.`);
      load();
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  const savePayment = async () => {
    const id = auth.get()?.id;
    if (!id) return;
    if (method === "PAYPAL" && !paypal.trim()) {
      toast.error("Enter your PayPal email.");
      return;
    }
    setSavingPay(true);
    try {
      await api.post(`/affiliates/${id}/payment`, { method, details: method === "PAYPAL" ? { info: paypal } : {} });
      toast.success("Payment method saved.");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSavingPay(false);
    }
  };

  const downloadInvoice = async (payoutId: string) => {
    try {
      const inv = await api.get(`/admin/payouts/${payoutId}/invoice`);
      const html = `<!doctype html><html><head><meta charset="utf-8"><title>${inv.invoiceNumber}</title>
<style>body{font-family:system-ui,-apple-system,sans-serif;padding:40px;color:#0f172a;max-width:640px;margin:auto}h1{color:#1A3C6E;margin:0}table{width:100%;border-collapse:collapse;margin-top:20px}td{padding:10px 0;border-bottom:1px solid #eee}.r{text-align:right}.big{font-size:22px;font-weight:700}</style></head>
<body><h1>${inv.program}</h1><p style="color:#64748b">Payout invoice · <b>${inv.invoiceNumber}</b> · ${inv.date}</p>
<table>
<tr><td>Affiliate</td><td class="r">${inv.affiliate} (${inv.email})</td></tr>
<tr><td>Method</td><td class="r">${inv.method}${inv.reference ? " · " + inv.reference : ""}</td></tr>
<tr><td>Status</td><td class="r">${inv.status}</td></tr>
<tr><td class="big">Amount paid</td><td class="r big">₹${Number(inv.amount).toLocaleString("en-IN")}</td></tr>
</table>
<p style="margin-top:36px;color:#94a3b8;font-size:12px">Generated by Partner Nook · ${inv.shop}</p></body></html>`;
      const blob = new Blob([html], { type: "text/html" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${inv.invoiceNumber}.html`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  const downloadCsv = () => {
    if (!d) return;
    const head = "Order,Date,Order value,Commission,Status";
    const body = d.orders.map((o) => `#${o.orderId.slice(-6)},${o.date},${o.total},${o.commission},${o.status}`).join("\n");
    const blob = new Blob([head + "\n" + body], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "my-earnings.csv";
    a.click();
    URL.revokeObjectURL(url);
  };

  if (!d) return <div className="space-y-4"><Skeleton className="h-8 w-40" /><div className="grid grid-cols-3 gap-4"><Skeleton className="h-24" /><Skeleton className="h-24" /><Skeleton className="h-24" /></div></div>;

  const eligible = d.balance >= d.minPayout;

  const Option = ({ value, title, desc, icon }: { value: "STORE_CREDIT" | "PAYPAL"; title: string; desc: string; icon: React.ReactNode }) => (
    <button
      type="button"
      onClick={() => setMethod(value)}
      className={cn(
        "flex items-start gap-3 rounded-xl border p-4 text-left transition",
        method === value ? "border-[var(--brand)] bg-[var(--brand-50)]/50 ring-1 ring-[var(--brand)]/20" : "border-gray-200 hover:border-gray-300",
      )}
    >
      <span className={cn("mt-0.5 flex h-9 w-9 items-center justify-center rounded-lg", method === value ? "bg-[var(--brand)] text-white" : "bg-gray-100 text-gray-500")}>{icon}</span>
      <span>
        <span className="block text-sm font-semibold text-gray-900">{title}</span>
        <span className="mt-0.5 block text-xs text-gray-500">{desc}</span>
      </span>
    </button>
  );

  return (
    <div>
      <PageHeader
        title="Payments"
        subtitle="Track earnings and get paid"
        actions={<Button variant="secondary" icon={<Download className="h-4 w-4" />} onClick={downloadCsv}>Download earnings (CSV)</Button>}
      />

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
        <StatCard label="Available balance" value={inr(d.balance)} icon={<Wallet className="h-5 w-5" />} accent="#d97706" />
        <StatCard label="Lifetime earnings" value={inr(d.stats.earnings)} icon={<IndianRupee className="h-5 w-5" />} accent="#1A3C6E" />
        <StatCard label="Minimum payout" value={inr(d.minPayout)} icon={<BadgeCheck className="h-5 w-5" />} accent="#16a34a" />
      </div>

      <div className="mt-4 grid gap-4 lg:grid-cols-2">
        <Card title="Request a payout">
          <p className="text-sm text-gray-500">
            {eligible ? `You can request a payout of ${inr(d.balance)}.` : `You need ${inr(d.minPayout)} to request a payout. Current balance: ${inr(d.balance)}.`}
          </p>
          <div className="mt-4">
            <Button icon={<Send className="h-4 w-4" />} disabled={!eligible} onClick={requestPayout}>Request payout</Button>
          </div>
        </Card>

        <Card title="How you want to be paid" subtitle="Choose your payout method">
          {!d.payoutMethods.includes("STORE_CREDIT") && !d.payoutMethods.includes("PAYPAL") ? (
            <p className="text-sm text-gray-500">The brand pays affiliates manually — no setup needed here.</p>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2">
              {d.payoutMethods.includes("STORE_CREDIT") && <Option value="STORE_CREDIT" title="Store credit" desc="Get a store discount coupon to spend here" icon={<Gift className="h-5 w-5" />} />}
              {d.payoutMethods.includes("PAYPAL") && <Option value="PAYPAL" title="PayPal" desc="Get paid to your PayPal account" icon={<Wallet className="h-5 w-5" />} />}
            </div>
          )}
          {method === "PAYPAL" && d.payoutMethods.includes("PAYPAL") && (
            <div className="mt-4">
              <FormField label="PayPal email">
                <Input value={paypal} onChange={(e) => setPaypal(e.target.value)} placeholder="you@paypal.com" />
              </FormField>
            </div>
          )}
          <div className="mt-4">
            <Button loading={savingPay} onClick={savePayment}>Save payment method</Button>
          </div>
        </Card>
      </div>

      <div className="mt-4">
        <Card title="Payout history">
          {d.payouts.length === 0 ? (
            <EmptyState icon={<Wallet className="h-6 w-6" />} title="No payouts yet" description="Your payouts — including store-credit coupons — will appear here." />
          ) : (
            <ul className="divide-y divide-gray-50">
              {d.payouts.map((p) => (
                <li key={p.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
                  <div>
                    <span className="font-medium text-gray-900">{inr(p.amount)}</span>
                    <span className="ml-2 text-xs text-gray-400">{p.date}</span>
                    {p.method === "STORE_CREDIT" && p.reference && (
                      <div className="mt-1 flex items-center gap-2">
                        <span className="rounded bg-gray-100 px-2 py-0.5 font-mono text-xs font-semibold text-gray-700">{p.reference}</span>
                        <button onClick={() => { navigator.clipboard?.writeText(p.reference!); toast.success("Coupon copied."); }} className="text-gray-400 hover:text-gray-600"><Copy className="h-3.5 w-3.5" /></button>
                        <span className="text-xs text-gray-400">redeem at checkout</span>
                      </div>
                    )}
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge tone={p.method === "STORE_CREDIT" ? "brand" : "info"}>{p.method === "STORE_CREDIT" ? "Store credit" : p.method === "PAYPAL" ? "PayPal" : "Manual"}</Badge>
                    <Badge tone={p.status === "PAID" ? "success" : "warning"}>{p.status}</Badge>
                    {p.status === "PAID" && (
                      <button onClick={() => downloadInvoice(p.id)} className="inline-flex items-center gap-1 rounded-lg border border-gray-300 px-2 py-1 text-xs font-medium text-gray-600 hover:bg-gray-50">
                        <Download className="h-3.5 w-3.5" /> Invoice
                      </button>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>
    </div>
  );
}
