import { CheckCircle2, XCircle } from 'lucide-react';
import { toast } from 'sonner';

import { useEffect, useRef } from 'react';

import { Head, Link, 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 } from '@/Components/ui/card';
import { EmptyState } from '@/Components/ui/empty-state';
import { usePolling } from '@/hooks/usePolling';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackProductEvent } from '@/lib/analytics';
import { AI_JOB_VIEWED, ERROR_DISPLAYED } from '@/lib/event-catalog';
import { formatDateTime } from '@/lib/format';
import { couldnt } from '@/lib/messages';
import type { PageProps, SiteBasic } from '@/types';

interface Draft {
  id: number;
  content: string;
  token_usage: { prompt_tokens: number; completion_tokens: number } | null;
  created_at: string;
  recommendation: {
    id: number;
    page_url: string;
    title: string;
    action_type: string;
  } | null;
}

interface AiJob {
  id: number;
  status: string;
  model: string;
  provider: string;
  total_recommendations: number;
  completed_recommendations: number;
  failed_recommendations: number;
  progress_percent: number;
  error: string | null;
  created_at: string;
  completed_at: string | null;
}

interface Props {
  site: SiteBasic;
  aiJob: AiJob;
  drafts: Draft[];
}

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

export default function JobShow({ site, aiJob, drafts }: Props) {
  const { polling_interval_ms } = usePage<PageProps>().props;
  const isActive = ['pending', 'processing'].includes(aiJob.status);

  useEffect(() => {
    trackProductEvent(AI_JOB_VIEWED, { job_id: aiJob.id, site_id: String(site.id) });
  }, [aiJob.id, site.id]);

  usePolling(isActive, polling_interval_ms, ['aiJob', 'drafts']);

  // Celebrate when draft generation completes or notify on failure
  const prevStatusRef = useRef(aiJob.status);
  useEffect(() => {
    const prev = prevStatusRef.current;
    const current = aiJob.status;
    if (prev && prev !== current) {
      if (['pending', 'processing'].includes(prev) && current === 'completed') {
        const count = aiJob.completed_recommendations;
        toast.success(`${count} draft${count === 1 ? '' : 's'} generated.`);
      } else if (['pending', 'processing'].includes(prev) && current === 'failed') {
        toast.error(couldnt('generate', 'drafts'));
        trackProductEvent(ERROR_DISPLAYED, {
          error_type: 'draft_generation_failed',
          site_id: String(site.id),
        });
      }
    }
    prevStatusRef.current = current;
  }, [aiJob.status, aiJob.completed_recommendations, site.id]);

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

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

        <div className="flex items-center gap-3 mb-6">
          <h1 className="text-2xl font-bold tracking-tight">AI Job #{aiJob.id}</h1>
          <Badge variant={statusVariant(aiJob.status)}>{aiJob.status}</Badge>
        </div>

        <div className="rounded-lg border bg-card p-4 mb-6">
          <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">{aiJob.model}</dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Progress</dt>
              <dd className="font-medium">
                {aiJob.completed_recommendations}/{aiJob.total_recommendations}
              </dd>
            </div>
            <div>
              <dt className="text-muted-foreground">Started</dt>
              <dd className="font-medium">{formatDateTime(aiJob.created_at)}</dd>
            </div>
            {aiJob.completed_at && (
              <div>
                <dt className="text-muted-foreground">Completed</dt>
                <dd className="font-medium">{formatDateTime(aiJob.completed_at)}</dd>
              </div>
            )}
          </dl>

          {aiJob.error && <p className="mt-3 text-sm text-destructive">{aiJob.error}</p>}

          {isActive && (
            <div className="mt-3">
              <div className="h-2 w-full rounded-full bg-muted">
                <div
                  className="h-2 rounded-full bg-primary transition-all"
                  // progress % is dynamic — Tailwind arbitrary values require static strings
                  style={{ width: `${aiJob.progress_percent}%` }}
                />
              </div>
            </div>
          )}
        </div>

        {/* Outcome summary for completed jobs */}
        {aiJob.status === 'completed' && (
          <Card
            className={`mb-6 ${aiJob.failed_recommendations > 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">
                {aiJob.failed_recommendations > 0 ? (
                  <XCircle 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">
                    {aiJob.failed_recommendations === 0
                      ? `All ${aiJob.total_recommendations} drafts generated successfully`
                      : `${aiJob.completed_recommendations} of ${aiJob.total_recommendations} drafts generated — ${aiJob.failed_recommendations} failed`}
                  </p>
                  <p className="text-sm text-muted-foreground mt-1">
                    {drafts.length > 0
                      ? 'Review the drafts below, then publish them to WordPress or edit in the content editor.'
                      : 'No drafts were produced. Check the error details above.'}
                  </p>
                  {drafts.length > 0 && (
                    <div className="flex gap-2 mt-3">
                      <Button size="sm" asChild>
                        <Link href={route('ai-drafts.show', [site.id, drafts[0].id])}>
                          Review First Draft
                        </Link>
                      </Button>
                      <Button variant="outline" size="sm" asChild>
                        <Link href={route('recommendations.index', site.id)}>
                          Back to Recommendations
                        </Link>
                      </Button>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Outcome summary for failed jobs */}
        {aiJob.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">Draft generation failed</p>
                  <p className="text-sm text-muted-foreground mt-1">
                    {drafts.length > 0
                      ? `${drafts.length} draft${drafts.length !== 1 ? 's were' : ' was'} generated before the job failed. You can still review ${drafts.length === 1 ? 'it' : 'them'} below.`
                      : 'Check that your API key is valid and has sufficient quota, then try again from the recommendations page.'}
                  </p>
                  <Button variant="outline" size="sm" className="mt-3" asChild>
                    <Link href={route('recommendations.index', site.id)}>
                      Back to Recommendations
                    </Link>
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        <h2 className="text-lg font-semibold mb-3">Generated Drafts</h2>

        {drafts.length === 0 ? (
          <EmptyState
            title="No drafts yet"
            description={
              isActive
                ? 'Drafts will appear here as they are generated.'
                : 'No drafts were generated for this job.'
            }
          />
        ) : (
          <div className="space-y-3">
            {drafts.map((draft) => (
              <Link
                key={draft.id}
                href={route('ai-drafts.show', [site.id, draft.id])}
                className="block rounded-lg border bg-card p-4 hover:bg-accent/50 transition-colors"
              >
                <div className="flex items-center justify-between">
                  <div>
                    <p className="font-medium">
                      {draft.recommendation?.title ?? `Draft #${draft.id}`}
                    </p>
                    {draft.recommendation && (
                      <p className="text-sm text-muted-foreground">
                        {draft.recommendation.page_url}
                      </p>
                    )}
                  </div>
                  {draft.token_usage && (
                    <span className="text-xs text-muted-foreground">
                      {draft.token_usage.prompt_tokens + draft.token_usage.completion_tokens} tokens
                    </span>
                  )}
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </>
  );
}

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