import { Link2 } from 'lucide-react';

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

import { AdminDataTable } from '@/Components/admin/AdminDataTable';
import { AdminStatsGrid, type StatCard } from '@/Components/admin/AdminStatsGrid';
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 {
  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 SharedReportLinkRow {
  id: number;
  report_id: number;
  report_name: string | null;
  token: string;
  is_password_protected: boolean;
  is_expired: boolean;
  view_count: number;
  expires_at: string | null;
  last_viewed_at: string | null;
  created_at: string;
}

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

interface Stats {
  total: number;
  active: number;
  expired: number;
  password_protected: number;
}

interface Props {
  links: PaginatedLinks;
  filters: { status: string };
  stats: Stats;
}

export default function SharedReportLinksIndex({ links, filters, stats }: Props) {
  const isNavigating = useNavigationState();

  const { updateFilter, handlePage } = useAdminFilters({
    route: route('admin.shared-report-links.index'),
    filters,
  });

  const exportParams: Record<string, string> = {};
  if (filters.status) exportParams.status = filters.status;

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

  const statCards: StatCard[] = [
    { title: 'Total', value: stats.total },
    { title: 'Active', value: stats.active },
    { title: 'Expired', value: stats.expired },
    { title: 'Password Protected', value: stats.password_protected },
  ];

  function handleRevoke(id: number) {
    if (!confirm('Revoke this shared report link? Viewers will lose access immediately.')) return;
    router.delete(route('admin.shared-report-links.destroy', { sharedReportLink: id }));
  }

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

        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <PageHeader
            title="Shared Report Links"
            description="Token-based public report sharing links."
          />
          <div className="flex flex-wrap items-center gap-2">
            <Select
              value={filters.status || 'all'}
              onValueChange={(value) => updateFilter({ status: value === 'all' ? '' : value })}
            >
              <SelectTrigger className="w-44">
                <SelectValue placeholder="Filter status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="expired">Expired</SelectItem>
                <SelectItem value="password_protected">Password Protected</SelectItem>
              </SelectContent>
            </Select>
            <ExportButton href={route('admin.shared-report-links.export')} params={exportParams} />
          </div>
        </div>

        <AdminStatsGrid stats={statCards} />

        <AdminDataTable
          isEmpty={links.data.length === 0}
          isNavigating={isNavigating}
          pagination={links}
          onPage={handlePage}
          paginationLabel="shared report links"
          emptyIcon={Link2}
          emptyTitle="No shared report links found"
        >
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Report</TableHead>
                <TableHead>Token</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Views</TableHead>
                <TableHead>Expires</TableHead>
                <TableHead>Last Viewed</TableHead>
                <TableHead>Created</TableHead>
                <TableHead className="w-20" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {links.data.map((link) => (
                <TableRow key={link.id}>
                  <TableCell className="font-medium">{link.report_name ?? `Report #${link.report_id}`}</TableCell>
                  <TableCell className="font-mono text-xs text-muted-foreground">
                    {link.token.slice(0, 12)}…
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      <Badge variant={link.is_expired ? 'destructive' : 'default'}>
                        {link.is_expired ? 'Expired' : 'Active'}
                      </Badge>
                      {link.is_password_protected && (
                        <Badge variant="outline">Protected</Badge>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">{link.view_count}</TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {link.expires_at ? formatRelativeTime(link.expires_at) : '—'}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {link.last_viewed_at ? formatRelativeTime(link.last_viewed_at) : '—'}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {formatRelativeTime(link.created_at)}
                  </TableCell>
                  <TableCell>
                    {!link.is_expired && (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-destructive hover:text-destructive"
                        onClick={() => handleRevoke(link.id)}
                      >
                        Revoke
                      </Button>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </AdminDataTable>
      </div>
    </AdminLayout>
  );
}
