import { Package } from 'lucide-react';

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

import PageHeader from '@/Components/layout/PageHeader';
import { Badge } from '@/Components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/Components/ui/breadcrumb';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import AdminLayout from '@/Layouts/AdminLayout';
import { getAdminStatusVariant } from '@/lib/adminStatusBadge';
import { formatDate, formatNumber } from '@/lib/format';

interface BatchJobDetail {
  id: number;
  site_id: number | null;
  site_name: string | null;
  site_domain: string | null;
  user_id: number | null;
  user_email: string | null;
  status: string;
  total_jobs: number;
  completed_jobs: number;
  failed_jobs: number;
  total_estimated_cost: string | null;
  total_actual_cost: string | null;
  total_estimated_tokens: number | null;
  total_actual_tokens: number | null;
  error_summary: Record<string, unknown> | null;
  retry_eligible: boolean;
  started_at: string | null;
  completed_at: string | null;
  created_at: string;
}

interface Props {
  job: BatchJobDetail;
}

export default function BatchJobsShow({ job }: Props) {
  const progressPercent =
    job.total_jobs > 0 ? Math.round((job.completed_jobs / job.total_jobs) * 100) : 0;

  return (
    <AdminLayout>
      <Head title={`Batch Job #${job.id}`} />
      <div className="container py-6 space-y-6">
        <Breadcrumb>
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href="/admin">Admin</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbLink asChild>
                <Link href={route('admin.batch-jobs.index')}>Batch Jobs</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>Batch #{job.id}</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <PageHeader
          title={`Batch Job #${job.id}`}
          description={`Created ${formatDate(job.created_at)}`}
        />

        <div className="grid gap-6 md:grid-cols-3">
          <div className="md:col-span-1 space-y-4">
            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Details</CardTitle>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                <div>
                  <p className="text-xs text-muted-foreground">Site</p>
                  {job.site_id ? (
                    <a
                      href={route('admin.sites.show', { site: job.site_id })}
                      className="text-primary hover:underline font-medium"
                    >
                      {job.site_name ?? '—'}
                    </a>
                  ) : (
                    <span className="font-medium">{job.site_name ?? '—'}</span>
                  )}
                  {job.site_domain && (
                    <p className="text-xs text-muted-foreground">{job.site_domain}</p>
                  )}
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">User</p>
                  {job.user_id ? (
                    <a
                      href={route('admin.users.show', { user: job.user_id })}
                      className="text-primary hover:underline font-medium"
                    >
                      {job.user_email ?? '—'}
                    </a>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Status</p>
                  <Badge variant={getAdminStatusVariant(job.status)}>{job.status}</Badge>
                </div>
                {job.retry_eligible && (
                  <div>
                    <Badge variant="outline">Retry Eligible</Badge>
                  </div>
                )}
                <div>
                  <p className="text-xs text-muted-foreground">Started At</p>
                  <p className="text-xs">{job.started_at ? formatDate(job.started_at) : '—'}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Completed At</p>
                  <p className="text-xs">{job.completed_at ? formatDate(job.completed_at) : '—'}</p>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Cost</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Estimated</span>
                  <span className="font-mono">
                    {job.total_estimated_cost ? `$${job.total_estimated_cost}` : '—'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Actual</span>
                  <span className="font-mono font-medium">
                    {job.total_actual_cost ? `$${job.total_actual_cost}` : '—'}
                  </span>
                </div>
                {job.total_estimated_tokens !== null && (
                  <div className="flex justify-between border-t pt-2">
                    <span className="text-muted-foreground">Est. Tokens</span>
                    <span className="font-mono text-xs">
                      {formatNumber(job.total_estimated_tokens ?? 0)}
                    </span>
                  </div>
                )}
                {job.total_actual_tokens !== null && (
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Actual Tokens</span>
                    <span className="font-mono text-xs">
                      {formatNumber(job.total_actual_tokens ?? 0)}
                    </span>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <div className="md:col-span-2 space-y-4">
            <Card>
              <CardHeader>
                <div className="flex items-center gap-2">
                  <Package className="h-4 w-4 text-muted-foreground" />
                  <CardTitle className="text-sm font-medium">Progress</CardTitle>
                </div>
              </CardHeader>
              <CardContent className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Completed</span>
                  <span className="font-mono font-medium">
                    {job.completed_jobs} / {job.total_jobs}
                  </span>
                </div>
                {job.total_jobs > 0 && (
                  <div className="w-full bg-muted rounded-full h-2">
                    <div
                      className="bg-primary rounded-full h-2 transition-all"
                      style={{ width: `${progressPercent}%` }}
                    />
                  </div>
                )}
                {job.failed_jobs > 0 && (
                  <div className="flex justify-between text-destructive">
                    <span>Failed</span>
                    <span className="font-mono font-medium">{job.failed_jobs}</span>
                  </div>
                )}
                <p className="text-xs text-muted-foreground">{progressPercent}% complete</p>
              </CardContent>
            </Card>

            {job.error_summary && Object.keys(job.error_summary).length > 0 && (
              <Card className="border-destructive">
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-destructive">
                    Error Summary
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <dl className="space-y-2 text-sm">
                    {Object.entries(job.error_summary).map(([key, value]) => (
                      <div key={key}>
                        <dt className="text-xs text-muted-foreground capitalize">
                          {key.replace(/_/g, ' ')}
                        </dt>
                        <dd className="font-mono text-xs text-destructive">{String(value)}</dd>
                      </div>
                    ))}
                  </dl>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}
