'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useQueries, useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Search, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Spinner } from '@/components/ui/spinners';
import { fetchWithdrawals } from '@/network/apis/dashboard/marketplace/marketplace.apis';
import {
  Withdrawal,
  WithdrawalStatus,
} from '@/network/apis/dashboard/marketplace/type';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { StatusPill } from './StatusPill';
import { WithdrawalDetailSheet } from './WithdrawalDetailSheet';

const STATUS_CHIPS: { label: string; value: WithdrawalStatus | 'all' }[] = [
  { label: 'All', value: 'all' },
  { label: 'Requested', value: 'requested' },
  { label: 'Approved', value: 'approved' },
  { label: 'Paid', value: 'paid' },
  { label: 'Rejected', value: 'rejected' },
  { label: 'Cancelled', value: 'cancelled' },
];

const formatMoney = (amount: number, currency: string) =>
  new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency || 'SAR',
    maximumFractionDigits: 2,
  }).format(amount);

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

  const status = sp?.get('status') ?? 'all';
  const creatorId = sp?.get('creator_id') ?? '';
  const from = sp?.get('from') ?? '';
  const to = sp?.get('to') ?? '';
  const page = Number(sp?.get('page') ?? 1);

  const [creatorIdInput, setCreatorIdInput] = useState(creatorId);
  const [fromInput, setFromInput] = useState(from);
  const [toInput, setToInput] = useState(to);

  useEffect(() => {
    setCreatorIdInput(creatorId);
    setFromInput(from);
    setToInput(to);
  }, [creatorId, from, to]);

  const [selected, setSelected] = useState<Withdrawal | null>(null);

  const queryParams = useMemo(() => {
    const p: Record<string, unknown> = { page, per_page: 25 };
    if (status && status !== 'all') p.status = status;
    if (creatorId) p.creator_id = creatorId;
    if (from) p.from = from;
    if (to) p.to = to;
    return p;
  }, [page, status, creatorId, from, to]);

  const { data, isLoading, isFetching } = useQuery({
    queryKey: ['withdrawals', queryParams],
    queryFn: () => fetchWithdrawals(queryParams),
  });

  // KPI strip — count by status (per_page=1)
  const monthStart = useMemo(() => {
    const d = new Date();
    return format(new Date(d.getFullYear(), d.getMonth(), 1), 'yyyy-MM-dd');
  }, []);

  const kpiQueries = useQueries({
    queries: [
      {
        queryKey: ['withdrawals-kpi', 'requested'],
        queryFn: () =>
          fetchWithdrawals({ status: 'requested', per_page: 1 }),
        staleTime: 30_000,
      },
      {
        queryKey: ['withdrawals-kpi', 'approved'],
        queryFn: () => fetchWithdrawals({ status: 'approved', per_page: 1 }),
        staleTime: 30_000,
      },
      {
        queryKey: ['withdrawals-kpi', 'paid-month'],
        queryFn: () =>
          fetchWithdrawals({
            status: 'paid',
            from: monthStart,
            per_page: 100,
          }),
        staleTime: 60_000,
      },
    ],
  });

  const pendingCount = kpiQueries[0].data?.meta?.total ?? 0;
  const approvedCount = kpiQueries[1].data?.meta?.total ?? 0;
  const paidThisMonth = kpiQueries[2].data;
  const paidCount = paidThisMonth?.meta?.total ?? 0;
  const paidSum =
    paidThisMonth?.items?.reduce((acc, w) => acc + Number(w.amount || 0), 0) ?? 0;

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

  const handleApplyFilters = () => {
    updateUrl({
      creator_id: creatorIdInput,
      from: fromInput,
      to: toInput,
    });
  };

  const handleResetFilters = () => {
    setCreatorIdInput('');
    setFromInput('');
    setToInput('');
    router.push('?');
  };

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

  return (
    <div className="space-y-5">
      {/* KPI strip */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <KpiCard
          label="Pending"
          value={pendingCount}
          tone="gray"
        />
        <KpiCard
          label="Approved"
          value={approvedCount}
          tone="blue"
        />
        <KpiCard
          label="Paid (this month)"
          value={paidCount}
          tone="green"
        />
        <KpiCard
          label="Total paid (this month)"
          value={formatMoney(paidSum, 'SAR')}
          tone="green"
        />
      </div>

      {/* Filter chips */}
      <div className="flex flex-wrap gap-2">
        {STATUS_CHIPS.map((c) => (
          <Button
            key={c.value}
            variant={status === c.value ? 'primary' : 'outline'}
            size="sm"
            onClick={() => updateUrl({ status: c.value })}
          >
            {c.label}
          </Button>
        ))}
      </div>

      {/* Filter bar */}
      <Card>
        <CardContent className="pt-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 items-end">
            <div>
              <Label className="text-xs">Creator ID</Label>
              <Input
                value={creatorIdInput}
                onChange={(e) => setCreatorIdInput(e.target.value)}
                placeholder="e.g. 21"
              />
            </div>
            <div>
              <Label className="text-xs">From</Label>
              <Input
                type="date"
                value={fromInput}
                onChange={(e) => setFromInput(e.target.value)}
              />
            </div>
            <div>
              <Label className="text-xs">To</Label>
              <Input
                type="date"
                value={toInput}
                onChange={(e) => setToInput(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              <Button onClick={handleApplyFilters} className="flex-1">
                <Search className="size-4 mr-1" /> Apply
              </Button>
              <Button variant="outline" onClick={handleResetFilters}>
                <X className="size-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Table */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex items-center justify-center py-16">
              <Spinner className="size-8 animate-spin text-primary" />
            </div>
          ) : items.length === 0 ? (
            <div className="py-16 text-center text-muted-foreground">
              No withdrawals match your filters.
              {status === 'requested' ? ' You\u2019re caught up.' : ''}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#ID</TableHead>
                  <TableHead>Creator</TableHead>
                  <TableHead>Amount</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Requested at</TableHead>
                  <TableHead>Reviewer</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((w) => (
                  <TableRow
                    key={w.id}
                    className="cursor-pointer hover:bg-muted/40"
                    onClick={() => setSelected(w)}
                  >
                    <TableCell className="font-mono text-sm">
                      #{w.id}
                    </TableCell>
                    <TableCell>
                      <div className="font-medium">
                        {w.creator?.display_name || w.creator?.username}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        @{w.creator?.username}
                      </div>
                    </TableCell>
                    <TableCell className="font-medium">
                      {formatMoney(w.amount, w.currency)}
                    </TableCell>
                    <TableCell>
                      <StatusPill status={w.status} />
                    </TableCell>
                    <TableCell className="text-sm">
                      {(() => {
                        try {
                          return format(new Date(w.requested_at), 'PP p');
                        } catch {
                          return w.requested_at;
                        }
                      })()}
                    </TableCell>
                    <TableCell className="text-sm">
                      {w.reviewer?.name ?? '—'}
                    </TableCell>
                    <TableCell className="text-right">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelected(w);
                        }}
                      >
                        View
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {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}

      {isFetching && !isLoading ? (
        <div className="text-xs text-muted-foreground text-center">
          Refreshing…
        </div>
      ) : null}

      <WithdrawalDetailSheet
        withdrawal={selected}
        open={!!selected}
        onClose={() => setSelected(null)}
      />
    </div>
  );
}

function KpiCard({
  label,
  value,
  tone,
}: {
  label: string;
  value: string | number;
  tone: 'gray' | 'blue' | 'green';
}) {
  const toneClass =
    tone === 'green'
      ? 'text-green-700'
      : tone === 'blue'
        ? 'text-blue-700'
        : 'text-foreground';
  return (
    <Card>
      <CardContent className="pt-4">
        <div className="text-xs uppercase tracking-wide text-muted-foreground">
          {label}
        </div>
        <div className={`text-2xl font-semibold mt-1 ${toneClass}`}>
          {value}
        </div>
      </CardContent>
    </Card>
  );
}
