'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { PayoutListData } from '@/network/apis/dashboard/payouts/type';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

type TableCellData = {
  value: string | number | null;
  color?: 'warning' | 'success';
};

const maskIban = (iban?: string) => {
  if (!iban) return '-';
  const clean = iban.replace(/\s+/g, '');
  if (clean.length <= 8) return clean;
  const last4 = clean.slice(-4);
  return `${clean.slice(0, 4)} **** **** **** ${last4}`;
};

const formatAmount = (amount: number | null | undefined, currency?: string) => {
  if (amount == null) return '-';
  return `${amount} ${currency ?? ''}`.trim();
};

const statusToColor = (status?: string): TableCellData['color'] => {
  if (!status) return undefined;
  const s = status.toLowerCase();
  if (s === 'initiated' || s === 'pending' || s === 'processing')
    return 'warning';
  if (s === 'succeeded' || s === 'completed' || s === 'paid') return 'success';
  return undefined;
};

const PayoutsList = ({ payouts }: { payouts: PayoutListData }) => {
  const router = useRouter();

  const tableHead = [
    { column: 'Sequence #' },
    { column: 'User' },
    { column: 'Amount' },
    { column: 'Status' },
    { column: 'Destination' },
    { column: 'Created At' },
  ];

  const [tableData, setTableData] = useState<TableCellData[][]>([]);

  useEffect(() => {
    const items = payouts?.items ?? [];
    if (!items.length) {
      setTableData([]);
      return;
    }

    const data: TableCellData[][] = items.map((p) => {
      const userLabel =
        p?.user?.name && p?.user?.email
          ? `${p.user.name} (${p.user.email})`
          : p?.user?.name || p?.user?.email || '-';

      const dest = p?.destination_type
        ? `${p.destination_type}${p.destination_iban ? ` • ${maskIban(p.destination_iban)}` : ''}${p.destination_name ? ` • ${p.destination_name}` : ''}`
        : '-';

      return [
        { value: p.sequence_number ?? '-' },
        { value: userLabel },
        { value: formatAmount(p.amount as number, p.response_currency) },
        { value: p.status ?? '-', color: statusToColor(p.status) },
        { value: dest },
        { value: p.created_at ?? '-' },
      ];
    });

    setTableData(data);
  }, [payouts]);

  const renderRow = (row: TableCellData[], index: number) => {
    const payoutId = payouts?.items?.[index]?.id;

    return (
      <TableRow
        key={payoutId ?? index}
        // onClick={() => payoutId && router.push(`/payout/${payoutId}`)}
        // role="button"
        tabIndex={0}
        className="hover:bg-accent/80 focus:bg-accent/80"
        // onKeyDown={(e) => {
        //   if ((e.key === 'Enter' || e.key === ' ') && payoutId) {
        //     router.push(`/payout/${payoutId}`);
        //   }
        // }}
      >
        {row.map((cell, i) =>
          cell.color && cell.value ? (
            <TableCell key={i} className="text-start">
              <Badge variant={cell.color} appearance="outline">
                {cell.value}
              </Badge>
            </TableCell>
          ) : (
            <TableCell key={i} className="text-sm text-foreground">
              {cell.value ?? '-'}
            </TableCell>
          ),
        )}
      </TableRow>
    );
  };

  return (
    <Card>
      <CardHeader className="flex-row items-center justify-between">
        <CardTitle>Payouts</CardTitle>
        <Button variant="outline" onClick={() => router.push('/payout/add')}>
          Create Payout
        </Button>
      </CardHeader>

      <CardContent className="kt-scrollable-x-auto p-0">
        <Table>
          <TableHeader>
            <TableRow className="bg-accent/60">
              {tableHead.map((h) => (
                <TableHead key={h.column} className="min-w-50 h-10">
                  {h.column}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>

          <TableBody>
            {tableData.length > 0 ? (
              tableData.map((row, idx) => renderRow(row, idx))
            ) : (
              <TableRow>
                <TableCell
                  colSpan={tableHead.length}
                  className="text-center py-8 text-muted-foreground"
                >
                  No payouts found
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  );
};

export { PayoutsList };
