import { useEffect, useState } from 'react';

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

import RollbackConfirmModal from '@/Components/ContentHistory/RollbackConfirmModal';
import SnapshotList from '@/Components/ContentHistory/SnapshotList';
import SiteNav from '@/Components/Navigation/SiteNav';
import { Button } from '@/Components/ui/button';
import DashboardLayout from '@/Layouts/DashboardLayout';
import { trackEvent } from '@/lib/analytics';
import { CONTENT_HISTORY_VIEWED } from '@/lib/event-catalog';
import type { SiteBasic } from '@/types';

interface ContentSnapshot {
  id: number;
  title: string;
  content: string;
  meta_description: string | null;
  seo_meta_title: string | null;
  seo_robots: string | null;
  categories: string[] | null;
  tags: string[] | null;
  wp_post_status: string;
  wp_modified_at: string;
  created_at: string;
}

interface WpPost {
  id: number;
  wp_post_id: number;
  url: string;
  title: string;
  content: string;
  meta_description: string | null;
  seo_meta_title: string | null;
  post_status: string;
  wp_modified_at: string | null;
}

interface GscMetrics {
  clicks: number;
  impressions: number;
  ctr: number;
  position: number;
}

interface Props {
  site: SiteBasic;
  wpPost: WpPost;
  snapshots: ContentSnapshot[];
  currentMetrics?: GscMetrics | null;
}

export default function ContentHistoryIndex({ site, wpPost, snapshots, currentMetrics }: Props) {
  useEffect(() => {
    trackEvent(CONTENT_HISTORY_VIEWED, { site_id: String(site.id) });
  }, [site.id]);

  const [rollbackModalOpen, setRollbackModalOpen] = useState(false);
  const [targetSnapshot, setTargetSnapshot] = useState<ContentSnapshot | null>(null);

  const handleRollback = (snapshot: ContentSnapshot) => {
    setTargetSnapshot(snapshot);
    setRollbackModalOpen(true);
  };

  const handleCloseModal = () => {
    setRollbackModalOpen(false);
    setTargetSnapshot(null);
  };

  // Current snapshot is the most recent one (first in list)
  const currentSnapshot: ContentSnapshot | null = snapshots.length > 0 ? snapshots[0] : null;

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

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

        <div className="flex items-center justify-between gap-3 mb-6">
          <div>
            <div className="flex items-center gap-2 mb-2">
              <Button variant="outline" size="sm" asChild>
                <Link href={route('content-inventory.index', site.id)}>
                  &larr; Back to Content Inventory
                </Link>
              </Button>
            </div>
            <h1 className="text-2xl font-bold tracking-tight">Content History</h1>
            <p className="text-sm text-muted-foreground mt-1">{wpPost.title}</p>
            <p className="text-xs text-muted-foreground">{wpPost.url}</p>
          </div>
        </div>

        <SnapshotList
          snapshots={snapshots}
          currentSnapshotId={currentSnapshot?.id}
          onRollback={
            handleRollback as (snapshot: {
              id: number;
              title: string;
              content: string;
              meta_description: string | null;
              wp_modified_at: string;
              created_at: string;
            }) => void
          }
        />
      </div>

      {rollbackModalOpen && targetSnapshot && currentSnapshot && (
        <RollbackConfirmModal
          open={rollbackModalOpen}
          onOpenChange={(val) => {
            if (!val) handleCloseModal();
          }}
          siteId={site.id}
          snapshotId={targetSnapshot.id}
          currentSnapshot={currentSnapshot}
          targetSnapshot={targetSnapshot}
          currentMetrics={currentMetrics}
        />
      )}
    </>
  );
}

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