'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { fetchBrandWallets } from '@/network/apis/dashboard/marketplace/wallets.apis';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import { downloadCsv, formatDate, formatMoney } from './format';

const SORT_OPTIONS = [
  { label: 'Balance ↓', value: 'balance:desc' },
  { label: 'Balance ↑', value: 'balance:asc' },
  { label: 'Pending ↓', value: 'pending:desc' },
  { label: 'Last activity ↓', value: 'last_activity:desc' },
];

function safePage(raw: string | null | undefined): number {
  const n = Number(raw);
  return Number.isFinite(n) && n >= 1 ? Math.floor(n) : 1;
}

export function BrandWalletsList() {
  const router = useRouter();
  const sp = useSearchParams();

  const q = sp?.get('q') ?? '';
  const sort = sp?.get('sort') ?? 'balance:desc';
  const page = safePage(sp?.get('page'));

  const [qInput, setQInput] = useState(q);

  const params = useMemo(
    () => ({ q: q || undefined, sort, page, per_page: 25 }),
    [q, sort, page],
  );

  const { data, isLoading, error } = useQuery({
    queryKey: ['brand-wallets', params],
    queryFn: () => fetchBrandWallets(params),
    retry: false,
  });

  const updateUrl = (next: Record<string, string | null>) => {
    const p = new URLSearchParams(sp?.toString() ?? '');
    for (const [k, v] of Object.entries(next)) {
      if (!v) p.delete(k);
      else p.set(k, v);
    }
    if (!('page' in next)) p.delete('page');
    router.push(`?${p.toString()}`);
  };

  const handleExport = () => {
    if (!data?.items?.length) return;
    const rows: string[][] = [
      ['Brand', 'Email', 'Balance', 'Pending', 'Lifetime in', 'Lifetime out', 'Last activity'],
      ...data.items.map((b) => [
        b.brand_name,
        b.brand_email,
        String(b.balance),
        String(b.pending),
        String(b.lifetime_topped_up),
        String(b.lifetime_spent),
        b.last_activity_at ?? '',
      ]),
    ];
    downloadCsv(`brand-wallets-${Date.now()}.csv`, rows);
  };

  const items = data?.items ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-5">
      <div className="flex items-end justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-2xl font-semibold">Brand wallets</h1>
          <p className="text-sm text-muted-foreground">
            Balances and lifetime activity for every brand with a wallet.
          </p>
        </div>
        <Button variant="outline" onClick={handleExport} disabled={!items.length}>
          Export CSV
        </Button>
      </div>

      <Card>
        <CardContent className="flex flex-wrap items-center gap-3 py-4">
          <div className="relative flex-1 min-w-64">
            <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              value={qInput}
              onChange={(e) => setQInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === 'Enter') updateUrl({ q: qInput || null });
              }}
              placeholder="Search brand name or email…"
              className="pl-9"
            />
          </div>
          <Button variant="outline" onClick={() => updateUrl({ q: qInput || null })}>
            Search
          </Button>
          <Select
            value={sort}
            onValueChange={(v) => updateUrl({ sort: v })}
          >
            <SelectTrigger className="w-44">
              <SelectValue placeholder="Sort" />
            </SelectTrigger>
            <SelectContent>
              {SORT_OPTIONS.map((o) => (
                <SelectItem key={o.value} value={o.value}>
                  {o.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </CardContent>
      </Card>

      {isLoading ? (
        <div className="flex items-center justify-center py-16">
          <Spinner className="size-8 animate-spin text-primary" />
        </div>
      ) : error ? (
        <FetchError error={error} fallback="Could not load brand wallets" />
      ) : items.length === 0 ? (
        <Card>
          <CardContent className="py-16 text-center text-muted-foreground">
            No brand wallets match this filter.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Brand</TableHead>
                  <TableHead className="text-right">Balance</TableHead>
                  <TableHead className="text-right">Pending</TableHead>
                  <TableHead className="text-right">Lifetime in</TableHead>
                  <TableHead className="text-right">Lifetime out</TableHead>
                  <TableHead>Last activity</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((b) => (
                  <TableRow
                    key={b.brand_id}
                    className="cursor-pointer hover:bg-muted/30"
                    onClick={() =>
                      router.push(`/marketplace-admin/money/brand-wallets/${b.brand_id}`)
                    }
                  >
                    <TableCell>
                      <Link
                        href={`/marketplace-admin/money/brand-wallets/${b.brand_id}`}
                        className="font-medium hover:underline"
                        onClick={(e) => e.stopPropagation()}
                      >
                        {b.brand_name}
                      </Link>
                      <div className="text-xs text-muted-foreground">
                        {b.brand_email}
                      </div>
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatMoney(b.balance, b.currency)}
                    </TableCell>
                    <TableCell className="text-right tabular-nums text-muted-foreground">
                      {formatMoney(b.pending, b.currency)}
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatMoney(b.lifetime_topped_up, b.currency)}
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatMoney(b.lifetime_spent, b.currency)}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {formatDate(b.last_activity_at)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      {meta && meta.last_page > 1 ? (
        <div className="flex justify-center">
          <PaginationComponent
            currentPage={meta.current_page}
            totalPages={meta.last_page}
            onPageChange={(p) => updateUrl({ page: String(p) })}
          />
        </div>
      ) : null}
    </div>
  );
}
