"use client";

import { useCallback, useEffect, useState } from "react";
import { Receipt, Undo2, RotateCcw } from "lucide-react";
import { api } from "@/lib/api";
import { PageHeader, StatusBadge, Button, Select, Input } from "@/components/ui";
import { DataTable, type Column } from "@/components/data-table";
import { useConfirm } from "@/components/modal";
import { useToast } from "@/components/toast";

type Sale = {
  id: string;
  orderId: string;
  affiliate: string;
  date: string;
  total: number;
  commission: number;
  via: string;
  status: string;
};

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

export default function SalesPage() {
  const toast = useToast();
  const confirm = useConfirm();
  const [rows, setRows] = useState<Sale[]>([]);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState("");
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const p = new URLSearchParams();
      if (status) p.set("status", status);
      if (from) p.set("from", from);
      if (to) p.set("to", to);
      const qs = p.toString();
      setRows(await api.get(`/admin/sales${qs ? "?" + qs : ""}`));
    } finally {
      setLoading(false);
    }
  }, [status, from, to]);

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

  const refund = async (s: Sale) => {
    if (!(await confirm({ title: "Refund this order?", message: `Commission of ${inr(s.commission)} will be deducted from ${s.affiliate}'s balance.`, tone: "danger", confirmText: "Refund" }))) return;
    try {
      await api.post(`/admin/sales/${s.id}/refund`);
      toast.success("Order refunded — commission reversed.");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    }
  };
  const reapprove = async (s: Sale) => {
    try {
      await api.post(`/admin/sales/${s.id}/approve`);
      toast.success("Sale re-approved — commission restored.");
      load();
    } catch (e) {
      toast.error((e as Error).message);
    }
  };

  const columns: Column<Sale>[] = [
    { key: "orderId", header: "Order", accessor: (r) => r.orderId, render: (r) => <span className="font-mono text-xs text-gray-600">#{r.orderId.slice(-6)}</span> },
    { key: "affiliate", header: "Affiliate", sortable: true, accessor: (r) => r.affiliate, render: (r) => <span className="font-medium text-gray-900">{r.affiliate}</span> },
    { key: "date", header: "Date", sortable: true, accessor: (r) => r.date },
    { key: "total", header: "Order value", sortable: true, align: "right", accessor: (r) => r.total, render: (r) => inr(r.total) },
    { key: "commission", header: "Commission", sortable: true, align: "right", accessor: (r) => r.commission, render: (r) => <span className="font-medium text-green-700">{inr(r.commission)}</span> },
    { key: "via", header: "Via", accessor: (r) => r.via, render: (r) => <span className="capitalize text-gray-500">{r.via}</span> },
    { key: "status", header: "Status", sortable: true, accessor: (r) => r.status, render: (r) => <StatusBadge status={r.status} /> },
    {
      key: "actions",
      header: "",
      align: "right",
      render: (r) =>
        r.status === "REFUNDED" || r.status === "REJECTED" ? (
          <Button size="sm" variant="secondary" icon={<RotateCcw className="h-3.5 w-3.5" />} onClick={() => reapprove(r)}>
            Re-approve
          </Button>
        ) : (
          <Button size="sm" variant="secondary" icon={<Undo2 className="h-3.5 w-3.5" />} onClick={() => refund(r)}>
            Refund
          </Button>
        ),
    },
  ];

  return (
    <div>
      <PageHeader title="Sales" subtitle="All affiliate-attributed orders" />
      <DataTable
        columns={columns}
        rows={rows}
        rowKey={(r) => r.id}
        loading={loading}
        exportName="affiliate-sales"
        searchPlaceholder="Search order, affiliate…"
        filters={
          <>
            <Select value={status} onChange={(e) => setStatus(e.target.value)} className="h-9 w-36">
              <option value="">All statuses</option>
              <option value="APPROVED">Approved</option>
              <option value="PENDING">Pending</option>
              <option value="REJECTED">Rejected</option>
              <option value="REFUNDED">Refunded</option>
            </Select>
            <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="h-9 w-40" aria-label="From date" />
            <span className="text-sm text-gray-400">–</span>
            <Input type="date" value={to} onChange={(e) => setTo(e.target.value)} className="h-9 w-40" aria-label="To date" />
            {(from || to || status) && (
              <button onClick={() => { setStatus(""); setFrom(""); setTo(""); }} className="text-xs text-gray-500 hover:underline">
                Clear
              </button>
            )}
          </>
        }
        empty={{ icon: <Receipt className="h-6 w-6" />, title: "No sales", description: "Attributed orders will appear here." }}
      />
    </div>
  );
}
