"use client";

import { useCallback, useEffect, useState } from "react";
import { ShieldAlert, ShieldCheck } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, Badge, Button } from "@/components/ui";
import { DataTable, type Column } from "@/components/data-table";
import { useConfirm } from "@/components/modal";
import { useToast } from "@/components/toast";

type Flag = { id: string; affiliate: string; reason: string; ip: string | null; date: string };

const REASON: Record<string, string> = {
  self_referral: "Self-referral",
  same_ip_repeat: "Repeated orders, same IP",
};

export default function FraudPage() {
  const toast = useToast();
  const confirm = useConfirm();
  const [rows, setRows] = useState<Flag[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      setRows(await api.get("/admin/fraud"));
    } finally {
      setLoading(false);
    }
  }, []);

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

  const resolve = async (f: Flag) => {
    if (!(await confirm({ title: "Mark as resolved?", message: `Dismiss the ${REASON[f.reason] ?? f.reason} flag for ${f.affiliate}.`, confirmText: "Resolve" }))) return;
    try {
      await api.post(`/admin/fraud/${f.id}/resolve`);
      toast.success("Flag resolved.");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  const columns: Column<Flag>[] = [
    { key: "affiliate", header: "Affiliate", sortable: true, accessor: (r) => r.affiliate, render: (r) => <span className="font-medium text-gray-900">{r.affiliate}</span> },
    { key: "reason", header: "Reason", sortable: true, accessor: (r) => REASON[r.reason] ?? r.reason, render: (r) => <Badge tone="danger">{REASON[r.reason] ?? r.reason}</Badge> },
    { key: "ip", header: "IP address", accessor: (r) => r.ip ?? "", render: (r) => <span className="font-mono text-xs text-gray-600">{r.ip ?? "—"}</span> },
    { key: "date", header: "Date", sortable: true, accessor: (r) => r.date },
    {
      key: "actions",
      header: "",
      align: "right",
      render: (r) => (
        <Button size="sm" variant="secondary" icon={<ShieldCheck className="h-3.5 w-3.5" />} onClick={() => resolve(r)}>
          Resolve
        </Button>
      ),
    },
  ];

  return (
    <div>
      <PageHeader title="Fraud" subtitle="Unresolved suspicious activity" />
      <DataTable
        columns={columns}
        rows={rows}
        rowKey={(r) => r.id}
        loading={loading}
        exportName="fraud-flags"
        searchPlaceholder="Search affiliate, reason, IP…"
        empty={{ icon: <ShieldAlert className="h-6 w-6" />, title: "No unresolved flags", description: "Suspicious orders (self-referrals, same-IP bursts) will show up here." }}
      />
    </div>
  );
}
