'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { 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 { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Spinner } from '@/components/ui/spinners';
import { fetchCreatorVerifications } from '@/network/apis/dashboard/marketplace/creator-verifications.apis';
import type {
  CreatorVerification,
  CreatorVerificationStatus,
} from '@/network/apis/dashboard/marketplace/creator-verifications.types';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { StatusPill } from './StatusPill';
import { CreatorVerificationDetailSheet } from './CreatorVerificationDetailSheet';

const STATUS_CHIPS: {
  label: string;
  value: CreatorVerificationStatus | 'all';
}[] = [
  { label: 'All', value: 'all' },
  { label: 'Under review', value: 'pending' },
  { label: 'Needs completion', value: 'needs_completion' },
  { label: 'Verified', value: 'approved' },
  { label: 'Rejected', value: 'rejected' },
];

const safeDate = (value: string | null | undefined) => {
  if (!value) return '—';
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? value : format(d, 'dd MMM yyyy');
};

/**
 * The queue of creator identity submissions.
 *
 * Defaults to Pending rather than All: the reason to open this page is that
 * somebody is waiting, and a list led by months of settled rows buries them.
 */
export function CreatorVerificationsList() {
  const router = useRouter();
  const sp = useSearchParams();

  const status = sp?.get('status') ?? 'pending';
  const search = sp?.get('search') ?? '';
  const page = Number(sp?.get('page') ?? 1);

  const [searchInput, setSearchInput] = useState(search);
  useEffect(() => setSearchInput(search), [search]);

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

  const { data, isLoading, isError } = useQuery({
    queryKey: ['creator-verifications', status, search, page],
    queryFn: () =>
      fetchCreatorVerifications({
        page,
        per_page: 25,
        status: status === 'all' ? undefined : status,
        search: search || undefined,
      }),
  });

  const setParams = (next: Record<string, string | undefined>) => {
    const params = new URLSearchParams(sp?.toString() ?? '');
    Object.entries(next).forEach(([k, v]) => {
      if (v === undefined || v === '') params.delete(k);
      else params.set(k, v);
    });
    // Any filter change invalidates the page number — page 3 of the old
    // result set is not page 3 of the new one.
    if (!('page' in next)) params.delete('page');
    router.push(`?${params.toString()}`);
  };

  const counts = data?.counts;

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-2">
        {STATUS_CHIPS.map((chip) => {
          const active = status === chip.value;
          const count =
            chip.value === 'all'
              ? counts
                ? Object.values(counts).reduce((sum, n) => sum + (n ?? 0), 0)
                : undefined
              : counts?.[chip.value];

          return (
            <Button
              key={chip.value}
              size="sm"
              variant={active ? 'primary' : 'outline'}
              onClick={() => setParams({ status: chip.value })}
            >
              {chip.label}
              {count !== undefined && (
                <span className="ms-1.5 text-xs opacity-70">{count}</span>
              )}
            </Button>
          );
        })}

        <div className="ms-auto flex items-center gap-2">
          <Input
            className="h-9 w-[240px]"
            placeholder="Name, email or ID number"
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter') setParams({ search: searchInput.trim() });
            }}
          />
          <Button
            size="sm"
            variant="outline"
            onClick={() => setParams({ search: searchInput.trim() })}
          >
            <Search className="h-4 w-4" />
          </Button>
          {search && (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => setParams({ search: undefined })}
            >
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
      </div>

      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex justify-center py-12">
              <Spinner className="h-6 w-6" />
            </div>
          ) : isError ? (
            <p className="py-12 text-center text-sm text-muted-foreground">
              Could not load verifications.
            </p>
          ) : !data?.items?.length ? (
            <p className="py-12 text-center text-sm text-muted-foreground">
              {status === 'pending'
                ? 'Nothing waiting for review.'
                : 'No submissions match this filter.'}
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Creator</TableHead>
                  <TableHead>Name on ID</TableHead>
                  <TableHead>ID</TableHead>
                  <TableHead>Submitted</TableHead>
                  <TableHead>Docs</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-end">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.items.map((v) => (
                  <TableRow
                    key={v.id}
                    className="cursor-pointer"
                    onClick={() => setSelected(v)}
                  >
                    <TableCell>
                      <div className="font-medium">
                        {v.creator?.name ?? '—'}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        {v.creator?.email ?? '—'}
                      </div>
                    </TableCell>
                    <TableCell>{v.full_name ?? '—'}</TableCell>
                    <TableCell>
                      <div>{v.id_number ?? '—'}</div>
                      <div className="text-xs text-muted-foreground">
                        {v.id_type ?? ''}
                      </div>
                    </TableCell>
                    <TableCell>{safeDate(v.submitted_at)}</TableCell>
                    <TableCell>
                      {/* Zero documents is the row a reviewer wants to spot
                          from the list, not after opening it. */}
                      <span
                        className={
                          v.documents?.length ? '' : 'text-amber-700 font-medium'
                        }
                      >
                        {v.documents?.length ?? 0}
                      </span>
                    </TableCell>
                    <TableCell>
                      <StatusPill status={v.status} />
                    </TableCell>
                    <TableCell className="text-end">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelected(v);
                        }}
                      >
                        {v.status === 'pending' ? 'Review' : 'View'}
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {data?.meta && data.meta.last_page > 1 && (
        <PaginationComponent
          currentPage={data.meta.current_page}
          totalPages={data.meta.last_page}
          onPageChange={(p: number) => setParams({ page: String(p) })}
        />
      )}

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