import {
  AlertCircle,
  ArrowLeft,
  CheckCircle2,
  Clock,
  Loader2,
  RefreshCw,
  XCircle,
} from 'lucide-react';
import { toast } from 'sonner';

import { useEffect } from 'react';

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

import SiteNav from '@/Components/Navigation/SiteNav';
import { Badge } from '@/Components/ui/badge';
import { Button } from '@/Components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { usePolling } from '@/hooks/usePolling';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { BATCH_AI_DETAIL_VIEWED } from '@/lib/event-catalog';
import { formatDateTime, formatNumber } from '@/lib/format';
import type { PageProps, SiteBasic } from '@/types';

interface DraftData {
  id: number;
  recommendation: {
    id: number;
    page_url: string;
    title: string;
    action_type: string;
  } | null;
}

interface AiJobData {
  id: number;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  total_recommendations: number;
  completed_recommendations: number;
  error: string | null;
  total_prompt_tokens: number;
  total_completion_tokens: number;
  created_at: string;
  completed_at: string | null;
  drafts: DraftData[];
}

interface BatchJobData {
  id: number;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  total_jobs: number;
  completed_jobs: number;
  failed_jobs: number;
  pending_jobs: number;
  progress_percent: number;
  total_estimated_tokens: number;
  total_estimated_cost: number;
  total_actual_tokens: number;
  total_actual_cost: number;
  settings_snapshot: {
    model: string;
    temperature?: number;
    top_p?: number;
    max_output_tokens?: number;
  } | null;
  started_at: string | null;
  completed_at: string | null;
  created_at: string;
}

interface Props {
  site: SiteBasic;
  batchJob: BatchJobData;
  aiJobs: AiJobData[];
}

function formatTokens(tokens: number): string {
  if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
  if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}K`;
  return formatNumber(tokens);
}

function formatCost(cost: number): string {
  if (cost < 0.01) return '<$0.01';
  return `$${cost.toFixed(2)}`;
}

function statusVariant(status: string): 'default' | 'secondary' | 'success' | 'destructive' {
  switch (status) {
    case 'completed':
      return 'success';
    case 'processing':
      return 'default';
    case 'pending':
      return 'secondary';
    case 'failed':
      return 'destructive';
    default:
      return 'secondary';
  }
}

function StatusIcon({ status }: { status: string }) {
  switch (status) {
    case 'completed':
      return <CheckCircle2 className="h-4 w-4 text-green-600 dark:text-green-400" />;
    case 'processing':
      return <Loader2 className="h-4 w-4 text-blue-600 dark:text-blue-400 animate-spin" />;
    case 'failed':
      return <XCircle className="h-4 w-4 text-red-600 dark:text-red-400" />;
    default:
      return <Clock className="h-4 w-4 text-muted-foreground" />;
  }
}

const ACTION_TYPE_LABELS: Record<string, string> = {
  noindex: 'Remove Noindex',
  content_rewrite: 'AI Draft',
  meta_tag_optimization: 'Meta Tags',
  internal_linking: 'Internal Linking',
  thin_content: 'Thin Content',
  cannibalization_consolidation: 'Cannibalization',
  light_refresh: 'Light Refresh',
  section_refresh: 'Section Refresh',
  full_rewrite: 'Full Rewrite',
  reposition_intent: 'Reposition Intent',
};

export default function BatchShow({ site, batchJob, aiJobs }: Props) {
  useEffect(() => {
    trackEvent(BATCH_AI_DETAIL_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  const { polling_interval_ms } = usePage<PageProps>().props;
  const isActive = ['pending', 'processing'].includes(batchJob.status);

  usePolling(isActive, polling_interval_ms, ['batchJob', 'aiJobs']);

  const successfulJobs = aiJobs.filter((j) => j.status === 'completed').length;
  const failedJobs = aiJobs.filter((j) => j.status === 'failed');
  const totalDrafts = aiJobs.reduce((sum, j) => sum + j.drafts.length, 0);
  const tokensUsed = batchJob.total_actual_tokens || batchJob.total_estimated_tokens;
  const costIncurred = batchJob.total_actual_cost || batchJob.total_estimated_cost;

  return (
    <>
      <Head title={`${site.name} - Batch Job #${batchJob.id}`} />

      <div className="container py-6">
        <SiteNav
          siteId={site.id}
          canAnalyze
          canRecommend
          canCannibalization
          canOpportunityMap
          canGeographic
          canDevice
        />

        {/* Back link */}
        <Link
          href={route('batch-ai.index', site.id)}
          className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground mb-4 transition-colors"
        >
          <ArrowLeft className="h-4 w-4" />
          Back to Batch History
        </Link>

        {/* Header */}
        <div className="flex items-center gap-3 mb-6">
          <h1 className="text-2xl font-bold tracking-tight">Batch Job #{batchJob.id}</h1>
          <Badge variant={statusVariant(batchJob.status)}>
            {batchJob.status === 'processing' && <Loader2 className="mr-1 h-3 w-3 animate-spin" />}
            {batchJob.status}
          </Badge>
        </div>

        {/* Summary Cards */}
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">Progress</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">
                {batchJob.completed_jobs}/{batchJob.total_jobs}
              </div>
              <p className="text-xs text-muted-foreground">
                {successfulJobs} succeeded, {batchJob.failed_jobs} failed
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Drafts Generated
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{totalDrafts}</div>
              <p className="text-xs text-muted-foreground">Across all jobs</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                Tokens Used
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatTokens(tokensUsed)}</div>
              <p className="text-xs text-muted-foreground">
                {batchJob.total_actual_tokens > 0 ? 'Actual' : 'Estimated'}
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">Cost</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{formatCost(costIncurred)}</div>
              <p className="text-xs text-muted-foreground">
                {batchJob.total_actual_cost > 0 ? 'Actual' : 'Estimated'}
              </p>
            </CardContent>
          </Card>
        </div>

        {/* Progress bar for active batches */}
        {isActive && (
          <div className="mb-6 space-y-1">
            <div className="flex items-center justify-between text-sm">
              <span className="text-muted-foreground">Overall progress</span>
              <span className="font-medium">{batchJob.progress_percent}%</span>
            </div>
            <div className="h-2.5 w-full rounded-full bg-muted overflow-hidden">
              <div
                className="h-full bg-primary transition-all duration-300"
                // progress % is dynamic — Tailwind arbitrary values require static strings
                style={{ width: `${batchJob.progress_percent}%` }}
                role="progressbar"
                aria-valuenow={batchJob.progress_percent}
                aria-valuemin={0}
                aria-valuemax={100}
              />
            </div>
          </div>
        )}

        {/* Outcome summary for completed batches */}
        {batchJob.status === 'completed' && (
          <Card
            className={`mb-6 ${batchJob.failed_jobs > 0 ? 'border-amber-200 dark:border-amber-800' : 'border-green-200 dark:border-green-800'}`}
          >
            <CardContent className="pt-6">
              <div className="flex items-start gap-3">
                {batchJob.failed_jobs > 0 ? (
                  <AlertCircle className="h-5 w-5 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
                ) : (
                  <CheckCircle2 className="h-5 w-5 text-green-600 dark:text-green-400 mt-0.5 shrink-0" />
                )}
                <div>
                  <p className="font-medium">
                    {batchJob.failed_jobs === 0
                      ? `All ${batchJob.total_jobs} jobs completed successfully`
                      : `${successfulJobs} of ${batchJob.total_jobs} jobs completed — ${batchJob.failed_jobs} failed`}
                  </p>
                  <p className="text-sm text-muted-foreground mt-1">
                    {totalDrafts} draft{totalDrafts !== 1 ? 's' : ''} generated using{' '}
                    {formatTokens(tokensUsed)} tokens ({formatCost(costIncurred)}).
                    {totalDrafts > 0 && ' Review drafts below to approve and publish.'}
                  </p>
                  {batchJob.failed_jobs > 0 && (
                    <Button
                      variant="outline"
                      size="sm"
                      className="mt-3"
                      onClick={() =>
                        router.post(
                          route('batch-ai.show', [site.id, batchJob.id]) + '/retry',
                          {},
                          { onSuccess: () => toast.success('Failed jobs queued for retry.') },
                        )
                      }
                    >
                      <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
                      Retry Failed Jobs
                    </Button>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Failed batch message */}
        {batchJob.status === 'failed' && (
          <Card className="mb-6 border-destructive/50">
            <CardContent className="pt-6">
              <div className="flex items-start gap-3">
                <XCircle className="h-5 w-5 text-destructive mt-0.5 shrink-0" />
                <div>
                  <p className="font-medium text-destructive">Batch job failed</p>
                  <p className="text-sm text-muted-foreground mt-1">
                    {successfulJobs > 0
                      ? `${successfulJobs} job${successfulJobs !== 1 ? 's' : ''} completed before the batch failed. Review the errors below.`
                      : 'No jobs completed. Check individual job errors below for details.'}
                  </p>
                  <Button
                    variant="outline"
                    size="sm"
                    className="mt-3"
                    onClick={() =>
                      router.post(
                        route('batch-ai.show', [site.id, batchJob.id]) + '/retry',
                        {},
                        { onSuccess: () => toast.success('Failed jobs queued for retry.') },
                      )
                    }
                  >
                    <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
                    Retry Failed Jobs
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Settings snapshot */}
        {batchJob.settings_snapshot && (
          <div className="rounded-lg border bg-card p-4 mb-6">
            <h3 className="text-sm font-medium text-muted-foreground mb-2">Generation Settings</h3>
            <dl className="grid grid-cols-2 gap-x-6 gap-y-2 text-sm sm:grid-cols-4">
              <div>
                <dt className="text-muted-foreground">Model</dt>
                <dd className="font-medium">{batchJob.settings_snapshot.model}</dd>
              </div>
              {batchJob.settings_snapshot.temperature != null && (
                <div>
                  <dt className="text-muted-foreground">Temperature</dt>
                  <dd className="font-medium">{batchJob.settings_snapshot.temperature}</dd>
                </div>
              )}
              {batchJob.started_at && (
                <div>
                  <dt className="text-muted-foreground">Started</dt>
                  <dd className="font-medium">{formatDateTime(batchJob.started_at)}</dd>
                </div>
              )}
              {batchJob.completed_at && (
                <div>
                  <dt className="text-muted-foreground">Completed</dt>
                  <dd className="font-medium">{formatDateTime(batchJob.completed_at)}</dd>
                </div>
              )}
            </dl>
          </div>
        )}

        {/* AI Jobs list */}
        <h2 className="text-lg font-semibold mb-3">AI Jobs ({aiJobs.length})</h2>

        {aiJobs.length === 0 ? (
          <EmptyState
            title="No jobs yet"
            description={
              isActive
                ? 'Jobs will appear here as they are queued for processing.'
                : 'No AI jobs were created for this batch.'
            }
          />
        ) : (
          <div className="space-y-3">
            {/* Failed jobs first, then by status */}
            {[...failedJobs, ...aiJobs.filter((j) => j.status !== 'failed')].map((job) => (
              <div key={job.id} className="rounded-lg border bg-card p-4">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <StatusIcon status={job.status} />
                    <span className="font-medium text-sm">Job #{job.id}</span>
                    <Badge variant={statusVariant(job.status)} className="text-xs">
                      {job.status}
                    </Badge>
                  </div>
                  {(job.total_prompt_tokens > 0 || job.total_completion_tokens > 0) && (
                    <span className="text-xs text-muted-foreground">
                      {formatTokens(job.total_prompt_tokens + job.total_completion_tokens)} tokens
                    </span>
                  )}
                </div>

                {job.error && (
                  <div className="mb-3 rounded bg-destructive/10 border border-destructive/20 px-3 py-2 text-sm text-destructive">
                    {job.error}
                  </div>
                )}

                {/* Drafts within this job */}
                {job.drafts.length > 0 ? (
                  <div className="space-y-2">
                    {job.drafts.map((draft) => (
                      <Link
                        key={draft.id}
                        href={route('ai-drafts.show', [site.id, draft.id])}
                        className="block rounded border bg-background px-3 py-2 hover:bg-accent/50 transition-colors"
                      >
                        <div className="flex items-center justify-between text-sm">
                          <div className="min-w-0 flex-1">
                            <p className="font-medium truncate">
                              {draft.recommendation?.title ?? `Draft #${draft.id}`}
                            </p>
                            {draft.recommendation && (
                              <div className="flex items-center gap-2 mt-0.5">
                                <span className="text-xs text-muted-foreground truncate">
                                  {draft.recommendation.page_url}
                                </span>
                                <Badge variant="outline" className="text-xs shrink-0">
                                  {ACTION_TYPE_LABELS[draft.recommendation.action_type] ??
                                    draft.recommendation.action_type}
                                </Badge>
                              </div>
                            )}
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                ) : job.status === 'completed' ? (
                  <p className="text-sm text-muted-foreground">No drafts generated.</p>
                ) : null}
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
}

BatchShow.layout = (page: React.ReactNode) => <DashboardLayout>{page}</DashboardLayout>;
