import { BarChart3, FileText, Search, Zap } 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 { ChartErrorBoundary } from '@/Components/admin/ChartErrorBoundary';
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 { 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 { formatRelativeTime } from '@/lib/format';

interface AiDraftRow {
  id: number;
  site_id: number | null;
  site_name: string | null;
  site_domain: string | null;
  recommendation_id: number | null;
  recommendation_action_type: string | null;
  model_used: string | null;
  prompt_tokens: number | null;
  completion_tokens: number | null;
  status: string | null;
  publish_status: string | null;
  created_at: string;
}

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

interface Stats {
  total: number;
  generated_30d: number;
  published_30d: number;
  avg_tokens: number;
}

interface Props {
  drafts: PaginatedDrafts;
  filters: {
    search?: string;
    site_id?: string;
    status?: string;
    sort?: string;
    dir?: string;
  };
  stats: Stats;
}

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

  const statCards: StatCard[] = [
    { title: 'Total Drafts', value: stats.total, icon: FileText },
    { title: 'Generated (30d)', value: stats.generated_30d, icon: Zap },
    { title: 'Published (30d)', value: stats.published_30d, icon: BarChart3 },
    { title: 'Avg Tokens', value: stats.avg_tokens, icon: BarChart3 },
  ];

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

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

        <AdminStatsGrid stats={statCards} />

        <PageHeader
          title="AI Drafts"
          description="Browse all AI-generated content drafts"
          actions={
            <ExportButton
              href={route('admin.ai-drafts.export')}
              params={{
                ...(filters.search ? { search: filters.search } : {}),
                ...(filters.site_id ? { site_id: filters.site_id } : {}),
                ...(filters.status ? { status: filters.status } : {}),
              }}
            />
          }
        />

        <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 site name or domain..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-9"
            />
          </div>
          <Select
            value={filters.status ?? 'all'}
            onValueChange={(val) => updateFilter({ status: val === 'all' ? undefined : val })}
          >
            <SelectTrigger className="w-[160px]" aria-label="Filter by status">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="generated">Generated</SelectItem>
              <SelectItem value="reviewed">Reviewed</SelectItem>
              <SelectItem value="published">Published</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <ChartErrorBoundary label="Unable to load drafts table">
          <AdminDataTable
            isEmpty={drafts.data.length === 0}
            isNavigating={isNavigating}
            pagination={drafts}
            onPage={handlePage}
            paginationLabel="drafts"
            emptyIcon={FileText}
            emptyTitle="No AI drafts found"
            emptyDescription="No AI drafts match your filters."
          >
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Site</TableHead>
                  <TableHead>Model</TableHead>
                  <SortHeader column="completion_tokens" label="Tokens" currentSort={filters.sort} currentDir={filters.dir} onSort={handleSort} />
                  <TableHead>Status</TableHead>
                  <TableHead>Publish</TableHead>
                  <TableHead>Recommendation</TableHead>
                  <SortHeader column="created_at" label="Created" currentSort={filters.sort} currentDir={filters.dir} onSort={handleSort} />
                  <TableHead />
                </TableRow>
              </TableHeader>
              <TableBody>
                {drafts.data.map((draft) => (
                  <TableRow key={draft.id}>
                    <TableCell>
                      {draft.site_id ? (
                        <a
                          href={route('admin.sites.show', { site: draft.site_id })}
                          className="text-primary hover:underline text-sm"
                        >
                          {draft.site_name ?? '—'}
                        </a>
                      ) : (
                        <span className="text-sm text-muted-foreground">—</span>
                      )}
                    </TableCell>
                    <TableCell className="text-xs font-mono">{draft.model_used ?? '—'}</TableCell>
                    <TableCell className="text-xs font-mono">
                      {draft.prompt_tokens !== null || draft.completion_tokens !== null
                        ? `${draft.prompt_tokens ?? 0} / ${draft.completion_tokens ?? 0}`
                        : '—'}
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{draft.status ?? '—'}</Badge>
                    </TableCell>
                    <TableCell>
                      {draft.publish_status ? (
                        <Badge variant="secondary">{draft.publish_status}</Badge>
                      ) : (
                        <span className="text-sm text-muted-foreground">—</span>
                      )}
                    </TableCell>
                    <TableCell className="text-sm">
                      {draft.recommendation_action_type
                        ? draft.recommendation_action_type.replace(/_/g, ' ')
                        : '—'}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {formatRelativeTime(draft.created_at)}
                    </TableCell>
                    <TableCell>
                      <Link
                        href={route('admin.ai-drafts.show', { aiDraft: draft.id })}
                        className="text-xs text-primary hover:underline"
                      >
                        View →
                      </Link>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </AdminDataTable>
        </ChartErrorBoundary>
      </div>
    </AdminLayout>
  );
}
