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

import { useRef } from 'react';

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

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
import { SortHeader } from '@/Components/admin/SortHeader';
import PageHeader from '@/Components/layout/PageHeader';
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 {
  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, formatNumber } from '@/lib/format';

interface WpPostRow {
  id: number;
  site_id: number;
  site_name: string | null;
  title: string;
  url: string;
  word_count: number | null;
  post_type: string;
  post_status: string;
  wp_modified_at: string | null;
  created_at: string;
}

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

interface Props {
  posts: PaginatedPosts;
  filters: {
    search?: string;
    sort?: string;
    dir?: string;
  };
  stats: {
    total_posts: number;
    avg_word_count: number;
  };
}

export default function Index({ posts, filters, stats }: Props) {
  const searchInputRef = useRef<HTMLInputElement>(null);
  const { search, setSearch, handleSort, handlePage } = useAdminFilters({
    route: 'admin.wp-posts.index',
    filters,
  });
  const isNavigating = useNavigationState();

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

  const statCards: StatCard[] = [
    { title: 'Total Posts', value: stats.total_posts, icon: FileText },
    {
      title: 'Avg Word Count',
      value: stats.avg_word_count,
      format: formatNumber,
    },
  ];

  return (
    <AdminLayout>
      <Head title="WP Posts" />
      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>WordPress Posts</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>
        <PageHeader
          title="WordPress Posts"
          description="Content inventory across all sites"
          actions={
            <ExportButton
              href={route('admin.wp-posts.export')}
              params={{
                ...(filters.search ? { search: filters.search } : {}),
              }}
            />
          }
        />

        <AdminStatsGrid stats={statCards} columns="grid-cols-1 md:grid-cols-2" />

        <div className="flex items-center gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              ref={searchInputRef}
              placeholder="Search by title, URL, or site..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
            />
          </div>
        </div>

        <AdminDataTable
          isEmpty={posts.data.length === 0}
          isNavigating={isNavigating}
          pagination={posts}
          onPage={handlePage}
          paginationLabel="posts"
          emptyIcon={FileText}
          emptyTitle="No posts found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Site</TableHead>
                <SortHeader
                  column="word_count"
                  label="Words"
                  currentSort={filters.sort}
                  currentDir={filters.dir}
                  onSort={handleSort}
                />
                <TableHead>Type</TableHead>
                <SortHeader
                  column="wp_modified_at"
                  label="Modified"
                  currentSort={filters.sort}
                  currentDir={filters.dir}
                  onSort={handleSort}
                />
              </TableRow>
            </TableHeader>
            <TableBody>
              {posts.data.map((post) => (
                <TableRow key={post.id}>
                  <TableCell>
                    <Link
                      href={route('admin.wp-posts.show', post.id)}
                      className="text-sm font-medium max-w-[300px] truncate block hover:underline"
                      title={post.title}
                    >
                      {post.title}
                    </Link>
                    <p className="text-xs text-muted-foreground max-w-[300px] truncate">
                      {post.url}
                    </p>
                  </TableCell>
                  <TableCell className="text-sm">{post.site_name ?? '—'}</TableCell>
                  <TableCell className="text-sm font-mono">
                    {post.word_count != null ? formatNumber(post.word_count) : '—'}
                  </TableCell>
                  <TableCell className="text-sm">{post.post_type}</TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatRelativeTime(post.wp_modified_at)}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>
    </AdminLayout>
  );
}
