import { Bot } 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 AiJobDetail {
  id: number;
  site_id: number | null;
  site_name: string | null;
  site_domain: string | null;
  user_id: number | null;
  user_name: string | null;
  user_email: string | null;
  analysis_run_id: number | null;
  analysis_run_status: string | null;
  batch_job_id: number | null;
  status: string;
  model: string | null;
  provider: string | null;
  total_recommendations: number;
  completed_recommendations: number;
  total_prompt_tokens: number;
  total_completion_tokens: number;
  failure_reason: string | null;
  error: string | null;
  started_at: string | null;
  completed_at: string | null;
  created_at: string;
}

interface Props {
  job: AiJobDetail;
}

export default function AiJobsShow({ job }: Props) {
  const totalTokens = (job.total_prompt_tokens ?? 0) + (job.total_completion_tokens ?? 0);

  return (
    <AdminLayout>
      <Head title={`AI 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.ai-jobs.index')}>AI Jobs</Link>
              </BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>Job #{job.id}</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        <PageHeader
          title={`AI 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_name ?? job.user_email ?? '—'}
                    </a>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                  {job.user_email && job.user_name && (
                    <p className="text-xs text-muted-foreground">{job.user_email}</p>
                  )}
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Status</p>
                  <Badge variant={getAdminStatusVariant(job.status)}>{job.status}</Badge>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">Model</p>
                  <p className="font-mono text-xs">{job.model ?? '—'}</p>
                </div>
                {job.provider && (
                  <div>
                    <p className="text-xs text-muted-foreground">Provider</p>
                    <p className="font-mono text-xs">{job.provider}</p>
                  </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>

            {(job.analysis_run_id || job.batch_job_id) && (
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm font-medium">Related</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3 text-sm">
                  {job.analysis_run_id && (
                    <div>
                      <p className="text-xs text-muted-foreground">Analysis Run</p>
                      <a
                        href={route('admin.analysis-runs.show', { analysisRun: job.analysis_run_id })}
                        className="text-primary hover:underline font-mono text-xs"
                      >
                        #{job.analysis_run_id}
                      </a>
                      {job.analysis_run_status && (
                        <Badge variant={getAdminStatusVariant(job.analysis_run_status)} className="ml-2">
                          {job.analysis_run_status}
                        </Badge>
                      )}
                    </div>
                  )}
                  {job.batch_job_id && (
                    <div>
                      <p className="text-xs text-muted-foreground">Batch Job</p>
                      <a
                        href={route('admin.batch-jobs.show', { batchJob: job.batch_job_id })}
                        className="text-primary hover:underline font-mono text-xs"
                      >
                        #{job.batch_job_id}
                      </a>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}
          </div>

          <div className="md:col-span-2 space-y-4">
            <Card>
              <CardHeader>
                <div className="flex items-center gap-2">
                  <Bot className="h-4 w-4 text-muted-foreground" />
                  <CardTitle className="text-sm font-medium">Progress</CardTitle>
                </div>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Recommendations</span>
                  <span className="font-mono font-medium">
                    {job.completed_recommendations} / {job.total_recommendations}
                  </span>
                </div>
                {job.total_recommendations > 0 && (
                  <div className="w-full bg-muted rounded-full h-2">
                    <div
                      className="bg-primary rounded-full h-2 transition-all"
                      style={{ width: `${Math.round((job.completed_recommendations / job.total_recommendations) * 100)}%` }}
                    />
                  </div>
                )}
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="text-sm font-medium">Token Usage</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Prompt</span>
                  <span className="font-mono">{formatNumber(job.total_prompt_tokens ?? 0)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Completion</span>
                  <span className="font-mono">{formatNumber(job.total_completion_tokens ?? 0)}</span>
                </div>
                <div className="flex justify-between border-t pt-2 font-medium">
                  <span>Total</span>
                  <span className="font-mono">{formatNumber(totalTokens)}</span>
                </div>
              </CardContent>
            </Card>

            {(job.failure_reason || job.error) && (
              <Card className="border-destructive">
                <CardHeader>
                  <CardTitle className="text-sm font-medium text-destructive">Error Details</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3 text-sm">
                  {job.failure_reason && (
                    <div>
                      <p className="text-xs text-muted-foreground">Failure Reason</p>
                      <p className="text-destructive">{job.failure_reason}</p>
                    </div>
                  )}
                  {job.error && (
                    <div>
                      <p className="text-xs text-muted-foreground">Error</p>
                      <pre className="text-xs font-mono whitespace-pre-wrap break-words text-destructive">{job.error}</pre>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </AdminLayout>
  );
}
