"use client";

import { useCallback, useEffect, useState } from "react";
import { Boxes, Plus, Trash2 } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Card, Button, Badge, Input, Select, FormField, EmptyState, Skeleton } from "@/components/ui";
import { useToast } from "@/components/toast";
import { useConfirm } from "@/components/modal";

type Rule = {
  id: string;
  matchType: string;
  matchValue: string;
  affiliateId: string | null;
  affiliateName: string;
  commissionType: string;
  commissionValue: number;
};
type Aff = { id: string; name: string };

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

export default function ProductCommissionsPage() {
  const toast = useToast();
  const confirm = useConfirm();
  const [rows, setRows] = useState<Rule[] | null>(null);
  const [affiliates, setAffiliates] = useState<Aff[]>([]);
  const [form, setForm] = useState({ matchType: "PRODUCT", matchValue: "", affiliateId: "", commissionType: "PERCENT", commissionValue: "" });
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    const d = await api.get("/admin/product-commissions");
    setRows(d.rows);
    setAffiliates(d.affiliates);
  }, []);
  useEffect(() => {
    load();
  }, [load]);

  const add = async () => {
    if (!form.matchValue.trim()) {
      toast.error("Enter a product keyword or tag.");
      return;
    }
    if (!form.commissionValue) {
      toast.error("Enter a commission value.");
      return;
    }
    setSaving(true);
    try {
      await api.post("/admin/product-commissions", form);
      toast.success("Product commission added.");
      setForm({ matchType: "PRODUCT", matchValue: "", affiliateId: "", commissionType: "PERCENT", commissionValue: "" });
      load();
    } catch (e) {
      toast.error((e as Error).message);
    } finally {
      setSaving(false);
    }
  };

  const remove = async (r: Rule) => {
    if (!(await confirm({ title: `Delete this rule?`, message: `${r.matchValue} → ${r.commissionValue}${r.commissionType === "FLAT" ? "₹" : "%"}`, tone: "danger", confirmText: "Delete" }))) return;
    await api.del(`/admin/product-commissions/${r.id}`);
    toast.info("Rule removed.");
    load();
  };

  return (
    <div className="max-w-4xl">
      <PageHeader title="Product commissions" subtitle="Different commission for specific products or tags" />

      <div className="space-y-4">
        <Card title="Add a rule" subtitle="Overrides the default commission when an order contains a matching product/tag">
          <div className="grid gap-4 sm:grid-cols-2">
            <FormField label="Match by">
              <Select value={form.matchType} onChange={(e) => setForm({ ...form, matchType: e.target.value })}>
                <option value="PRODUCT">Product title contains</option>
                <option value="TAG">Order tag equals</option>
              </Select>
            </FormField>
            <FormField label={form.matchType === "TAG" ? "Tag" : "Product keyword"}>
              <Input value={form.matchValue} onChange={(e) => setForm({ ...form, matchValue: e.target.value })} placeholder={form.matchType === "TAG" ? "e.g. vip" : "e.g. Coffee Mug"} />
            </FormField>
            <FormField label="Affiliate" hint="Leave blank = all affiliates">
              <Select value={form.affiliateId} onChange={(e) => setForm({ ...form, affiliateId: e.target.value })}>
                <option value="">All affiliates</option>
                {affiliates.map((a) => (
                  <option key={a.id} value={a.id}>{a.name}</option>
                ))}
              </Select>
            </FormField>
            <div className="grid grid-cols-2 gap-3">
              <FormField label="Type">
                <Select value={form.commissionType} onChange={(e) => setForm({ ...form, commissionType: e.target.value })}>
                  <option value="PERCENT">Percent</option>
                  <option value="FLAT">Flat ₹</option>
                </Select>
              </FormField>
              <FormField label="Value">
                <Input type="number" min={0} value={form.commissionValue} onChange={(e) => setForm({ ...form, commissionValue: e.target.value })} placeholder="e.g. 15" />
              </FormField>
            </div>
          </div>
          <div className="mt-4">
            <Button icon={<Plus className="h-4 w-4" />} loading={saving} onClick={add}>Add rule</Button>
          </div>
        </Card>

        <Card title="Rules" subtitle="Applied on order sync — affiliate-specific rules win over ‘all’">
          {!rows ? (
            <Skeleton className="h-24" />
          ) : rows.length === 0 ? (
            <EmptyState icon={<Boxes className="h-6 w-6" />} title="No product commissions" description="Add a rule to pay a different rate on specific products or tags." />
          ) : (
            <ul className="divide-y divide-gray-50">
              {rows.map((r) => (
                <li key={r.id} className="flex flex-wrap items-center justify-between gap-3 py-3">
                  <div className="flex items-center gap-2">
                    <Badge tone="neutral">{r.matchType === "TAG" ? "Tag" : "Product"}</Badge>
                    <span className="text-sm font-medium text-gray-800">{r.matchValue}</span>
                    <span className="text-xs text-gray-400">→ {r.affiliateName}</span>
                  </div>
                  <div className="flex items-center gap-3">
                    <Badge tone="brand">{r.commissionType === "FLAT" ? inr(r.commissionValue) : `${r.commissionValue}%`}</Badge>
                    <button onClick={() => remove(r)} className="text-gray-400 hover:text-red-600"><Trash2 className="h-4 w-4" /></button>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </Card>
      </div>
    </div>
  );
}
