import { Search } from 'lucide-react';

import { useRef } from 'react';

import { Head, Link } from '@inertiajs/react';

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { ExportButton } from '@/Components/ui/export-button';
import { Input } from '@/Components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/Components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/Components/ui/table';
import { useAdminFilters } from '@/hooks/useAdminFilters';
import { useAdminKeyboardShortcuts } from '@/hooks/useAdminKeyboardShortcuts';
import { useNavigationState } from '@/hooks/useNavigationState';
import AdminLayout from '@/Layouts/AdminLayout';
import { getAdminStatusVariant } from '@/lib/adminStatusBadge';
import { formatRelativeTime } from '@/lib/format';

interface SerpSnapshotRow {
  id: number;
  site_id: number;
  site_name: string | null;
  site_domain: string | null;
  keyword: string;
  target_url: string | null;
  status: string;
  fetched_at: string | null;
  expires_at: string | null;
  created_at: string;
}

interface PaginatedSnapshots {
  data: SerpSnapshotRow[];
  current_page: number;
  last_page: number;
  from: number | null;
  to: number | null;
  total: number;
}

interface Props {
  snapshots: PaginatedSnapshots;
  filters: { status: string; search?: string };
}

export default function SerpSnapshotsIndex({ snapshots, filters }: Props) {
  const isNavigating = useNavigationState();
  const searchRef = useRef<HTMLInputElement>(null);

  const { search, setSearch, updateFilter, handlePage } = useAdminFilters({
    route: route('admin.serp-snapshots.index'),
    filters,
  });
  const exportParams: Record<string, string> = {};
  if (filters.search) exportParams.search = filters.search;
  if (filters.status) exportParams.status = filters.status;

  useAdminKeyboardShortcuts({
    onSearch: () => searchRef.current?.focus(),
    onNextPage: snapshots.current_page < snapshots.last_page ? () => handlePage(snapshots.current_page + 1) : undefined,
    onPrevPage: snapshots.current_page > 1 ? () => handlePage(snapshots.current_page - 1) : undefined,
  });

  const currentPage = snapshots.current_page;
  const lastPage = snapshots.last_page;
  useAdminKeyboardShortcuts({
    onNextPage: currentPage < lastPage ? () => handlePage(currentPage + 1) : undefined,
    onPrevPage: currentPage > 1 ? () => handlePage(currentPage - 1) : undefined,
  });

  return (
    <AdminLayout>
      <Head title="SERP Snapshots" />
      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>SERP Snapshots</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <PageHeader
            title="SERP Snapshots"
            description="DataForSEO SERP analysis snapshots for competitor benchmarking."
          />
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                ref={searchRef}
                placeholder="Search snapshots…"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9 w-52"
                aria-label="Search SERP snapshots"
              />
            </div>
            <Select
              value={filters.status || 'all'}
              onValueChange={(value) => updateFilter({ status: value === 'all' ? '' : value })}
            >
              <SelectTrigger className="w-40">
                <SelectValue placeholder="Filter status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="pending">Pending</SelectItem>
                <SelectItem value="processing">Processing</SelectItem>
                <SelectItem value="completed">Completed</SelectItem>
                <SelectItem value="failed">Failed</SelectItem>
              </SelectContent>
            </Select>
            <ExportButton href={route('admin.serp-snapshots.export')} params={exportParams} />
          </div>
        </div>

        <AdminDataTable
          isEmpty={snapshots.data.length === 0}
          isNavigating={isNavigating}
          pagination={snapshots}
          onPage={handlePage}
          paginationLabel="SERP snapshots"
          emptyIcon={Search}
          emptyTitle="No SERP snapshots found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Keyword</TableHead>
                <TableHead>Site</TableHead>
                <TableHead>Target URL</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Fetched</TableHead>
                <TableHead>Expires</TableHead>
                <TableHead>Created</TableHead>
                <TableHead className="w-16" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {snapshots.data.map((snapshot) => (
                <TableRow key={snapshot.id}>
                  <TableCell className="font-medium">{snapshot.keyword}</TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{snapshot.site_name}</div>
                      <div className="text-muted-foreground">{snapshot.site_domain}</div>
                    </div>
                  </TableCell>
                  <TableCell className="max-w-48 truncate text-sm text-muted-foreground">
                    {snapshot.target_url ?? '—'}
                  </TableCell>
                  <TableCell>
                    <Badge variant={getAdminStatusVariant(snapshot.status)}>{snapshot.status}</Badge>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {snapshot.fetched_at ? formatRelativeTime(snapshot.fetched_at) : '—'}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {snapshot.expires_at ? formatRelativeTime(snapshot.expires_at) : '—'}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatRelativeTime(snapshot.created_at)}
                  </TableCell>
                  <TableCell>
                    <Link
                      href={route('admin.serp-snapshots.show', { serpSnapshot: snapshot.id })}
                      className="text-xs text-primary hover:underline"
                    >
                      View →
                    </Link>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>
    </AdminLayout>
  );
}
