'use client';

import { useMemo } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { fetchTransfers } from '@/network/apis/dashboard/marketplace/wallets.apis';
import { LedgerAccountType } from '@/network/apis/dashboard/marketplace/wallets.types';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { downloadCsv, formatDateTime, formatMoney } from './format';

const ACCOUNT_CHIPS: { label: string; value: LedgerAccountType | 'all' }[] = [
  { label: 'All', value: 'all' },
  { label: 'Creator', value: 'creator' },
  { label: 'Platform', value: 'platform' },
  { label: 'VAT', value: 'vat' },
];

const ACCOUNT_BADGE: Record<LedgerAccountType, string> = {
  creator: 'bg-blue-100 text-blue-700 border-blue-200',
  platform: 'bg-emerald-100 text-emerald-700 border-emerald-200',
  vat: 'bg-amber-100 text-amber-800 border-amber-200',
};

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

function safeAccountType(raw: string | null | undefined): LedgerAccountType | undefined {
  return raw === 'creator' || raw === 'platform' || raw === 'vat' ? raw : undefined;
}

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

  const accountType = sp?.get('account_type') ?? 'all';
  const brandId = sp?.get('brand_id') ?? '';
  const creatorId = sp?.get('creator_id') ?? '';
  const crId = sp?.get('cr_id') ?? '';
  const from = sp?.get('from') ?? '';
  const to = sp?.get('to') ?? '';
  const page = safeNumberQs(sp?.get('page')) ?? 1;

  const params = useMemo(
    () => ({
      account_type: safeAccountType(accountType),
      brand_id: safeNumberQs(brandId),
      creator_id: safeNumberQs(creatorId),
      cr_id: safeNumberQs(crId),
      from: from || undefined,
      to: to || undefined,
      page,
      per_page: 25,
    }),
    [accountType, brandId, creatorId, crId, from, to, page],
  );

  const { data, isLoading, error } = useQuery({
    queryKey: ['transfers', params],
    queryFn: () => fetchTransfers(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 || v === 'all') p.delete(k);
      else p.set(k, v);
    }
    if (!('page' in next)) p.delete('page');
    router.push(`?${p.toString()}`);
  };

  const items = data?.items ?? [];
  const meta = data?.meta;
  const currency = items[0]?.currency ?? 'SAR';
  const sumCredits = items
    .filter((t) => t.type === 'credit')
    .reduce((acc, t) => acc + Number(t.amount || 0), 0);

  const handleExport = () => {
    if (!items.length) return;
    const rows: string[][] = [
      ['Posted', 'Account type', 'Account', 'Type', 'Amount', 'Currency', 'CR ID', 'CR title', 'Brand', 'Note'],
      ...items.map((t) => [
        t.posted_at,
        t.account_type,
        t.account_label,
        t.type,
        String(t.amount),
        t.currency,
        t.collaboration_request?.id != null
          ? String(t.collaboration_request.id)
          : '',
        t.collaboration_request?.title ?? '',
        t.collaboration_request?.brand_name ?? '',
        t.note ?? '',
      ]),
    ];
    downloadCsv(`ledger-${Date.now()}.csv`, rows);
  };

  return (
    <div className="space-y-5">
      <div className="flex items-end justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-2xl font-semibold">Collaboration ledger</h1>
          <p className="text-sm text-muted-foreground">
            Follow the money — every collaboration transfer across creators,
            platform, and VAT.
          </p>
        </div>
        <Button variant="outline" onClick={handleExport} disabled={!items.length}>
          Export CSV
        </Button>
      </div>

      <Card>
        <CardContent className="space-y-4 py-4">
          <div className="flex flex-wrap gap-2">
            {ACCOUNT_CHIPS.map((c) => (
              <Button
                key={c.value}
                size="sm"
                variant={accountType === c.value ? 'primary' : 'outline'}
                onClick={() => updateUrl({ account_type: c.value })}
              >
                {c.label}
              </Button>
            ))}
          </div>
          <div className="flex flex-wrap items-end gap-3">
            <div className="space-y-1">
              <Label>Brand ID</Label>
              <Input
                type="number"
                min="1"
                value={brandId}
                onChange={(e) => updateUrl({ brand_id: e.target.value || null })}
                className="w-32"
              />
            </div>
            <div className="space-y-1">
              <Label>Creator ID</Label>
              <Input
                type="number"
                min="1"
                value={creatorId}
                onChange={(e) =>
                  updateUrl({ creator_id: e.target.value || null })
                }
                className="w-32"
              />
            </div>
            <div className="space-y-1">
              <Label>CR ID</Label>
              <Input
                type="number"
                min="1"
                value={crId}
                onChange={(e) => updateUrl({ cr_id: e.target.value || null })}
                className="w-32"
              />
            </div>
            <div className="space-y-1">
              <Label>From</Label>
              <Input
                type="date"
                value={from}
                onChange={(e) => updateUrl({ from: e.target.value || null })}
                className="w-40"
              />
            </div>
            <div className="space-y-1">
              <Label>To</Label>
              <Input
                type="date"
                value={to}
                onChange={(e) => updateUrl({ to: e.target.value || null })}
                className="w-40"
              />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="flex flex-wrap items-center gap-6 py-4 text-sm">
          <div>
            <span className="text-muted-foreground">Credits in view: </span>
            <strong className="tabular-nums">
              {formatMoney(sumCredits, currency)}
            </strong>
          </div>
          <div>
            <span className="text-muted-foreground">Entries: </span>
            <strong className="tabular-nums">{meta?.total ?? items.length}</strong>
          </div>
        </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 ledger" />
      ) : items.length === 0 ? (
        <Card>
          <CardContent className="py-16 text-center text-muted-foreground">
            No ledger entries match this filter.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Posted</TableHead>
                  <TableHead>Account</TableHead>
                  <TableHead>Account name</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>For CR</TableHead>
                  <TableHead className="text-right">Amount</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((t) => (
                  <TableRow key={t.id}>
                    <TableCell className="text-sm whitespace-nowrap">
                      {formatDateTime(t.posted_at)}
                    </TableCell>
                    <TableCell>
                      <span
                        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${
                          ACCOUNT_BADGE[t.account_type] ?? ''
                        }`}
                      >
                        {t.account_type}
                      </span>
                    </TableCell>
                    <TableCell className="text-sm">{t.account_label}</TableCell>
                    <TableCell className="text-sm capitalize">
                      {t.type}
                    </TableCell>
                    <TableCell className="text-sm">
                      {t.collaboration_request ? (
                        <Link
                          href={`/marketplace-admin/money/cr/${t.collaboration_request.id}`}
                          className="hover:underline"
                        >
                          #{t.collaboration_request.id} —{' '}
                          {t.collaboration_request.title}
                        </Link>
                      ) : (
                        '—'
                      )}
                    </TableCell>
                    <TableCell
                      className={`text-right tabular-nums ${
                        t.type === 'credit' ? 'text-emerald-700' : 'text-red-700'
                      }`}
                    >
                      {t.type === 'credit' ? '+' : '−'}
                      {formatMoney(Math.abs(Number(t.amount)), t.currency)}
                    </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>
  );
}
