"use client";

import { useGetAeAttainmentQuery } from "@/api/rtk/sales-targets-api";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { formatMoney } from "@/components/sales-targets/sales-targets-helpers";
import { format } from "date-fns";
import { Loader2 } from "lucide-react";
import { useSearchParams } from "next/navigation";

interface RepTransactionsDialogProps {
  userId: string | null;
  userName: string;
  teamId?: string;
  year?: number;
  month?: number;
  onClose: () => void;
}

function resolvePeriod(
  yearProp: number | undefined,
  monthProp: number | undefined,
  searchParams: ReturnType<typeof useSearchParams>,
) {
  const rawYear = searchParams.get("year");
  const rawMonth = searchParams.get("month");
  const dt = new Date();
  const year =
    yearProp ??
    (rawYear ? parseInt(rawYear, 10) : undefined) ??
    dt.getFullYear();
  const month =
    monthProp ??
    (rawMonth ? parseInt(rawMonth, 10) : undefined) ??
    dt.getMonth() + 1;
  return {
    year: Number.isFinite(year) ? year : dt.getFullYear(),
    month: Math.min(12, Math.max(1, Number.isFinite(month) ? month : dt.getMonth() + 1)),
  };
}

export function RepTransactionsDialog({
  userId,
  userName,
  teamId,
  year: yearProp,
  month: monthProp,
  onClose,
}: RepTransactionsDialogProps) {
  const searchParams = useSearchParams();
  const { year, month } = resolvePeriod(yearProp, monthProp, searchParams);

  const { data, isLoading } = useGetAeAttainmentQuery(
    { userId: userId!, year, month, teamId },
    { skip: !userId },
  );

  return (
    <Dialog open={!!userId} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-4xl max-h-[85vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Transactions for {userName}</DialogTitle>
        </DialogHeader>

        <div className="flex-1 overflow-y-auto min-h-0">
          {isLoading ? (
            <div className="flex h-32 items-center justify-center">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : !data || data.transactions.length === 0 ? (
            <div className="flex h-32 items-center justify-center text-muted-foreground">
              No transactions found for this period.
            </div>
          ) : (
            <div className="rounded-md border">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b bg-muted/50 text-left font-medium text-muted-foreground">
                    <th className="p-4">Lead Name</th>
                    <th className="p-4">Date</th>
                    <th className="p-4 text-right">Total Deal Value</th>
                    <th className="p-4 text-right">Rep Share</th>
                  </tr>
                </thead>
                <tbody>
                  {data.transactions.map((tx) => (
                    <tr key={tx.transactionId} className="border-b last:border-0 hover:bg-muted/50 transition-colors">
                      <td className="p-4 font-medium">{tx.leadName}</td>
                      <td className="p-4 text-muted-foreground">
                        {format(new Date(tx.date), "MMM d, yyyy")}
                      </td>
                      <td className="p-4 text-right">{formatMoney(tx.amount)}</td>
                      <td className="p-4 text-right font-medium text-green-600 dark:text-green-400">
                        {formatMoney(tx.share)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
