'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { format, startOfMonth } from 'date-fns';
import {
  ArrowRight,
  Banknote,
  Coins,
  Receipt,
  Users,
  Wallet,
} from 'lucide-react';
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 { fetchMoneyOverview } from '@/network/apis/dashboard/marketplace/wallets.apis';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';

function formatMoney(value: number | undefined, currency = 'SAR'): string {
  if (value == null || Number.isNaN(value)) return '—';
  try {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency,
      maximumFractionDigits: 0,
    }).format(value);
  } catch {
    return `${value} ${currency}`;
  }
}

function todayISO(): string {
  return format(new Date(), 'yyyy-MM-dd');
}

function firstOfMonthISO(): string {
  return format(startOfMonth(new Date()), 'yyyy-MM-dd');
}

type KpiCardProps = {
  title: string;
  value: string;
  sub?: string;
  href?: string;
  icon: React.ElementType;
  tone?: 'default' | 'primary' | 'success' | 'warning';
};

function KpiCard({ title, value, sub, href, icon: Icon, tone = 'default' }: KpiCardProps) {
  const toneClass = {
    default: 'bg-muted/30 text-foreground',
    primary: 'bg-blue-50 text-blue-700',
    success: 'bg-emerald-50 text-emerald-700',
    warning: 'bg-amber-50 text-amber-700',
  }[tone];

  const inner = (
    <Card className="h-full transition hover:shadow-md">
      <CardContent className="flex items-start gap-4 p-5">
        <div className={`rounded-md p-2 ${toneClass}`}>
          <Icon className="size-5" />
        </div>
        <div className="flex-1">
          <div className="text-xs uppercase tracking-wider text-muted-foreground">
            {title}
          </div>
          <div className="mt-1 text-2xl font-semibold tabular-nums">{value}</div>
          {sub ? (
            <div className="mt-0.5 text-xs text-muted-foreground">{sub}</div>
          ) : null}
        </div>
        {href ? (
          <ArrowRight className="size-4 text-muted-foreground" />
        ) : null}
      </CardContent>
    </Card>
  );

  return href ? <Link href={href}>{inner}</Link> : inner;
}

export function MoneyOverview() {
  const [from, setFrom] = useState(firstOfMonthISO());
  const [to, setTo] = useState(todayISO());

  const params = useMemo(() => ({ from, to }), [from, to]);

  const { data, isLoading, error } = useQuery({
    queryKey: ['money-overview', params],
    queryFn: () => fetchMoneyOverview(params),
    retry: false,
  });

  const currency = data?.currency ?? 'SAR';
  const totals = data?.totals;
  const counts = data?.counts;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold">Money Center</h1>
        <p className="text-sm text-muted-foreground">
          A health snapshot of marketplace money flow.
        </p>
      </div>

      <Card>
        <CardContent className="flex flex-wrap items-end gap-4 py-4">
          <div className="space-y-1">
            <Label htmlFor="mc-from">From</Label>
            <Input
              id="mc-from"
              type="date"
              value={from}
              onChange={(e) => setFrom(e.target.value)}
              className="w-40"
            />
          </div>
          <div className="space-y-1">
            <Label htmlFor="mc-to">To</Label>
            <Input
              id="mc-to"
              type="date"
              value={to}
              onChange={(e) => setTo(e.target.value)}
              className="w-40"
            />
          </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 overview" />
      ) : (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <KpiCard
              title="Brand wallets"
              value={formatMoney(totals?.brand_wallets_balance, currency)}
              sub={`+${formatMoney(totals?.brand_wallets_pending, currency)} pending`}
              href="/marketplace-admin/money/brand-wallets"
              icon={Wallet}
              tone="primary"
            />
            <KpiCard
              title="Platform revenue"
              value={formatMoney(totals?.platform_revenue_period, currency)}
              sub="this period"
              href="/marketplace-admin/money/reports/platform-revenue"
              icon={Coins}
              tone="success"
            />
            <KpiCard
              title="VAT collected"
              value={formatMoney(totals?.vat_collected_period, currency)}
              sub="this period"
              href="/marketplace-admin/money/reports/vat-collected"
              icon={Receipt}
              tone="warning"
            />
            <KpiCard
              title="Creator earnings"
              value={formatMoney(totals?.creator_earnings_period, currency)}
              sub={`${formatMoney(totals?.creator_outstanding, currency)} outstanding`}
              href="/marketplace-admin/money/ledger?account_type=creator"
              icon={Banknote}
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <CountChip
              label="Brands w/ wallet"
              value={counts?.brands_with_wallet}
              icon={Users}
            />
            <CountChip
              label="Active collabs"
              value={counts?.active_collabs}
              icon={Banknote}
            />
            <CountChip
              label="Completed collabs"
              value={counts?.completed_collabs}
              icon={Banknote}
            />
            <CountChip
              label="Pending withdrawals"
              value={counts?.pending_withdrawals}
              icon={Wallet}
              href="/marketplace-admin/withdrawals?status=requested"
            />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <Card>
              <CardContent className="p-0">
                <div className="px-4 py-3 border-b text-sm font-semibold">
                  Top brand spenders
                </div>
                {data?.top_brand_spenders &&
                data.top_brand_spenders.length > 0 ? (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Brand</TableHead>
                        <TableHead className="text-right">Amount</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.top_brand_spenders.map((b) => (
                        <TableRow key={b.brand_id}>
                          <TableCell>
                            <Link
                              href={`/marketplace-admin/money/brand-wallets/${b.brand_id}`}
                              className="hover:underline"
                            >
                              {b.brand_name}
                            </Link>
                            {b.brand_email ? (
                              <div className="text-xs text-muted-foreground">
                                {b.brand_email}
                              </div>
                            ) : null}
                          </TableCell>
                          <TableCell className="text-right tabular-nums">
                            {formatMoney(b.total_spent, currency)}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                ) : (
                  <div className="px-4 py-8 text-center text-sm text-muted-foreground">
                    No data for this period.
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-0">
                <div className="px-4 py-3 border-b text-sm font-semibold">
                  Top earning creators
                </div>
                {data?.top_earning_creators &&
                data.top_earning_creators.length > 0 ? (
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>Creator</TableHead>
                        <TableHead className="text-right">Amount</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {data.top_earning_creators.map((c) => (
                        <TableRow key={c.creator_id}>
                          <TableCell>{c.creator_name}</TableCell>
                          <TableCell className="text-right tabular-nums">
                            {formatMoney(c.total_earned, currency)}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                ) : (
                  <div className="px-4 py-8 text-center text-sm text-muted-foreground">
                    No data for this period.
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </>
      )}
    </div>
  );
}

function CountChip({
  label,
  value,
  icon: Icon,
  href,
}: {
  label: string;
  value: number | undefined;
  icon: React.ElementType;
  href?: string;
}) {
  const inner = (
    <Card className="h-full transition hover:shadow-sm">
      <CardContent className="flex items-center gap-3 py-4">
        <Icon className="size-4 text-muted-foreground" />
        <div className="flex-1 text-sm">{label}</div>
        <div className="text-lg font-semibold tabular-nums">
          {value ?? '—'}
        </div>
      </CardContent>
    </Card>
  );
  return href ? <Link href={href}>{inner}</Link> : inner;
}
