"use client";

import { useEffect, useState } from "react";
import { Gift, Wallet, HandCoins } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Input, FormField, Skeleton } from "@/components/ui";
import { SettingsTabs } from "@/components/settings-tabs";
import { cn } from "@/components/cn";
import { useToast } from "@/components/toast";

const METHODS = [
  { key: "STORE_CREDIT", label: "Store credit", desc: "Pay affiliates with a real Shopify gift card / discount", icon: <Gift className="h-5 w-5" /> },
  { key: "PAYPAL", label: "PayPal", desc: "Pay affiliates to their PayPal account", icon: <Wallet className="h-5 w-5" /> },
  { key: "UPI", label: "UPI", desc: "Indian UPI ID", icon: <HandCoins className="h-5 w-5" /> },
  { key: "BANK", label: "Bank transfer", desc: "Bank account / IMPS / NEFT", icon: <HandCoins className="h-5 w-5" /> },
  { key: "PAYONEER", label: "Payoneer", desc: "Global payouts via Payoneer", icon: <Wallet className="h-5 w-5" /> },
  { key: "WISE", label: "Wise", desc: "International transfer via Wise", icon: <Wallet className="h-5 w-5" /> },
  { key: "CASH", label: "Cash", desc: "Offline cash payout", icon: <HandCoins className="h-5 w-5" /> },
  { key: "CHEQUE", label: "Cheque", desc: "Pay by cheque", icon: <HandCoins className="h-5 w-5" /> },
  { key: "MANUAL", label: "Manual / Other", desc: "Mark as paid for any offline transfer", icon: <HandCoins className="h-5 w-5" /> },
];

export default function PaymentSettingsPage() {
  const toast = useToast();
  const [methods, setMethods] = useState<string[] | null>(null);
  const [minPayout, setMinPayout] = useState(0);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    api.get("/admin/payment-settings").then((d) => {
      setMethods(d.payoutMethods);
      setMinPayout(d.minPayout);
    });
  }, []);

  const toggle = (k: string) =>
    setMethods((m) => (!m ? m : m.includes(k) ? m.filter((x) => x !== k) : [...m, k]));

  const save = async () => {
    if (!methods) return;
    if (methods.length === 0) {
      toast.error("Enable at least one payout method.");
      return;
    }
    setSaving(true);
    try {
      await api.put("/admin/payment-settings", { payoutMethods: methods, minPayout });
      toast.success("Payment settings saved.");
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  if (!methods) return <div className="space-y-4"><Skeleton className="h-8 w-40" /><Skeleton className="h-56" /></div>;

  return (
    <div className="max-w-4xl">
      <PageHeader title="Settings" subtitle="Payout methods & threshold" actions={<Button onClick={save} loading={saving}>Save</Button>} />
      <SettingsTabs />

      <div className="space-y-4">
        <Card title="Supported payout methods" subtitle="Affiliates choose from the ones you enable">
          <div className="space-y-3">
            {METHODS.map((m) => {
              const on = methods.includes(m.key);
              return (
                <button
                  key={m.key}
                  type="button"
                  onClick={() => toggle(m.key)}
                  className={cn(
                    "flex w-full items-center gap-3 rounded-xl border p-4 text-left transition",
                    on ? "border-[var(--brand)] bg-[var(--brand-50)]/50 ring-1 ring-[var(--brand)]/20" : "border-gray-200 hover:border-gray-300",
                  )}
                >
                  <span className={cn("flex h-9 w-9 items-center justify-center rounded-lg", on ? "bg-[var(--brand)] text-white" : "bg-gray-100 text-gray-500")}>{m.icon}</span>
                  <span className="flex-1">
                    <span className="block text-sm font-semibold text-gray-900">{m.label}</span>
                    <span className="text-xs text-gray-500">{m.desc}</span>
                  </span>
                  <span className={cn("h-5 w-5 rounded-full border-2", on ? "border-[var(--brand)] bg-[var(--brand)]" : "border-gray-300")}>
                    {on && <span className="block h-full w-full scale-50 rounded-full bg-white" />}
                  </span>
                </button>
              );
            })}
          </div>
        </Card>

        <Card title="Threshold">
          <FormField label="Minimum payout (₹)" hint="Affiliates must reach this balance to request a payout">
            <Input type="number" min={0} value={minPayout} onChange={(e) => setMinPayout(Number(e.target.value))} />
          </FormField>
        </Card>
      </div>
    </div>
  );
}
