import { History as HistoryIcon } from 'lucide-react';

import { useEffect } from 'react';

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


import BatchHistoryCard from '@/Components/Batch/BatchHistoryCard';
import SiteNav from '@/Components/Navigation/SiteNav';
import InertiaPagination from '@/Components/Shared/InertiaPagination';
import { Button } from '@/Components/ui/button';
import { EmptyState } from '@/Components/ui/empty-state';
import { useNavigationState } from '@/hooks/useNavigationState';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { FEATURE_USED } from '@/lib/event-catalog';
import type { PageProps, SiteBasic } from '@/types';

interface BatchJob {
  id: number;
  created_at: string;
  completed_at: string | null;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  total_jobs: number;
  completed_jobs: number;
  failed_jobs: number;
  total_actual_tokens: number | null;
  total_estimated_tokens: number;
  total_actual_cost: number | null;
  total_estimated_cost: number;
}

interface PaginatedBatchJobs {
  data: BatchJob[];
  links: Array<{ url: string | null; label: string; active: boolean }>;
  current_page: number;
  last_page: number;
}

interface Props {
  site: SiteBasic;
  batchJobs: PaginatedBatchJobs;
  hasActiveBatches: boolean;
}

export default function History({ site, batchJobs, hasActiveBatches }: Props) {
  const { polling_interval_ms } = usePage<PageProps>().props;
  const isNavigating = useNavigationState();

  // Track feature usage
  useEffect(() => {
    trackEvent(FEATURE_USED, { feature: 'batch_ai' });
  }, []);

  // Poll when there are active batches
  useEffect(() => {
    if (hasActiveBatches) {
      const interval = setInterval(() => {
        router.reload({ only: ['batchJobs', 'hasActiveBatches'] });
      }, polling_interval_ms);
      return () => clearInterval(interval);
    }
  }, [hasActiveBatches, polling_interval_ms]);

  return (
    <>
      <Head title={`${site.name} - Batch AI History`} />

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

        <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground">Batch AI History</h1>
            <p className="text-sm text-muted-foreground mt-1">
              View past and current batch AI draft generation jobs
            </p>
          </div>
          <Button variant="outline" asChild>
            <Link href={route('recommendations.index', site.id)}>Back to Recommendations</Link>
          </Button>
        </div>

        {batchJobs.data.length === 0 ? (
          <EmptyState
            icon={HistoryIcon}
            title="No batch jobs yet"
            description="You haven't run any batch AI draft generation jobs yet. Generate drafts for multiple recommendations at once from the Recommendations page."
            action={
              <Button asChild>
                <Link href={route('recommendations.index', site.id)}>Go to Recommendations</Link>
              </Button>
            }
          />
        ) : (
          <div className={`space-y-4 transition-opacity ${isNavigating ? 'opacity-50' : ''}`}>
            {batchJobs.data.map((batchJob) => (
              <BatchHistoryCard key={batchJob.id} batchJob={batchJob} siteId={site.id} />
            ))}

            <InertiaPagination
              links={batchJobs.links}
              currentPage={batchJobs.current_page}
              lastPage={batchJobs.last_page}
            />
          </div>
        )}
      </div>
    </>
  );
}

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