'use client';

import Link from 'next/link';
import type { Route } from 'next';
import { useQuery } from '@tanstack/react-query';
import { ArrowLeft, FilePlus } from 'lucide-react';

import { PageHeader } from '@/components/shared/page-header';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { EmptyState } from '@/components/shared/empty-state';
import { apiFetch } from '@/lib/api/client';
import type { ReportTemplate } from '@/lib/db/schema/reports';

interface ListResponse {
  data: ReportTemplate[];
}

export function ReportTemplatesPageClient({ portSlug }: { portSlug: string }) {
  const { data, isLoading } = useQuery<ListResponse>({
    queryKey: ['report-templates'],
    queryFn: () => apiFetch<ListResponse>('/api/v1/reports/templates?limit=50'),
  });

  const rows = data?.data ?? [];

  return (
    <div className="space-y-4">
      <PageHeader
        eyebrow="Reports"
        title="Templates"
        description="Saved report configurations. Pick one to re-run with one click."
        actions={
          <Button asChild variant="outline" size="sm">
            <Link href={`/${portSlug}/reports` as Route}>
              <ArrowLeft className="mr-1.5 h-4 w-4" aria-hidden />
              All reports
            </Link>
          </Button>
        }
      />

      {isLoading ? (
        <Skeleton className="h-[200px] w-full" aria-hidden />
      ) : rows.length === 0 ? (
        <EmptyState
          icon={FilePlus}
          title="No saved templates yet"
          description="When generating a report from a builder, save the configuration to re-use it."
        />
      ) : (
        <Card>
          <CardContent className="p-0">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Kind</TableHead>
                  <TableHead>Visibility</TableHead>
                  <TableHead>Created</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((t) => (
                  <TableRow key={t.id}>
                    <TableCell>
                      <Link
                        href={`/${portSlug}/reports/${t.kind}?templateId=${t.id}` as Route}
                        className="font-medium text-primary hover:underline"
                      >
                        {t.name}
                      </Link>
                      {t.description ? (
                        <p className="mt-0.5 text-xs text-muted-foreground">{t.description}</p>
                      ) : null}
                    </TableCell>
                    <TableCell className="capitalize">{t.kind}</TableCell>
                    <TableCell>
                      <Badge variant={t.visibility === 'team' ? 'default' : 'outline'}>
                        {t.visibility}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {new Date(t.createdAt).toLocaleDateString()}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
