import { Camera, Search } from 'lucide-react';

import { useRef } from 'react';

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

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { SortHeader } from '@/Components/admin/SortHeader';
import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { Button } from '@/Components/ui/button';
import { ExportButton } from '@/Components/ui/export-button';
import { Input } from '@/Components/ui/input';
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 { formatRelativeTime } from '@/lib/format';

interface ContentSnapshotRow {
  id: number;
  site_id: number;
  site_name: string | null;
  site_domain: string | null;
  wp_post_id: number;
  title: string | null;
  wp_post_status: string | null;
  url: string | null;
  created_at: string;
}

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

interface Props {
  snapshots: PaginatedSnapshots;
  filters: { site_id: string; search?: string; sort?: string; dir?: string };
}

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

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

  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,
  });

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

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <PageHeader
            title="Content Snapshots"
            description="Version history snapshots of WordPress post content."
          />
          <div className="flex 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 content snapshots"
              />
            </div>
            <ExportButton href={route('admin.content-snapshots.export')} params={exportParams} />
          </div>
        </div>

        <AdminDataTable
          isEmpty={snapshots.data.length === 0}
          isNavigating={isNavigating}
          pagination={snapshots}
          onPage={handlePage}
          paginationLabel="content snapshots"
          emptyIcon={Camera}
          emptyTitle="No content snapshots found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Site</TableHead>
                <TableHead>WP Post ID</TableHead>
                <TableHead>Post Status</TableHead>
                <TableHead>URL</TableHead>
                <SortHeader column="created_at" label="Created" currentSort={filters.sort} currentDir={filters.dir} onSort={handleSort} />
                <TableHead className="w-16" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {snapshots.data.map((snapshot) => (
                <TableRow key={snapshot.id}>
                  <TableCell className="font-medium">
                    {snapshot.title ?? <span className="text-muted-foreground">Untitled</span>}
                  </TableCell>
                  <TableCell>
                    <div className="text-sm">
                      <div>{snapshot.site_name}</div>
                      <div className="text-muted-foreground">{snapshot.site_domain}</div>
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {snapshot.wp_post_id}
                  </TableCell>
                  <TableCell>
                    {snapshot.wp_post_status ? (
                      <Badge variant="secondary">{snapshot.wp_post_status}</Badge>
                    ) : (
                      <span className="text-muted-foreground">—</span>
                    )}
                  </TableCell>
                  <TableCell className="max-w-48 truncate text-sm text-muted-foreground">
                    {snapshot.url ?? '—'}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatRelativeTime(snapshot.created_at)}
                  </TableCell>
                  <TableCell>
                    <Button variant="ghost" size="sm" asChild>
                      <Link href={route('admin.sites.show', { site: snapshot.site_id })}>
                        Site
                      </Link>
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>
    </AdminLayout>
  );
}
