import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import type { StructuredBlock, AmazonData, MapData, XPostData, YouTubeData } from './types';
import { AmazonProductsCard } from './AmazonProductsCard';
import { AmazonProductsDetail } from './AmazonProductsDetail';
import { MapPlacesCard } from './MapPlacesCard';
import { MapPlacesDetail } from './MapPlacesDetail';
import { XPostsCard } from './XPostsCard';
import { XPostsDetail } from './XPostsDetail';
import { YouTubeVideosCard } from './YouTubeVideosCard';
import { YouTubeVideosDetail } from './YouTubeVideosDetail';
import { EmbedModal } from './EmbedModal';

async function fetchStructuredBlock(taskId: number, refId: string): Promise<StructuredBlock> {
  const res = await fetch(`/api/local/tasks/${taskId}/files/raw?section=logs&path=structured/${refId}.json`);
  if (!res.ok) throw new Error(`Failed to fetch embed: ${res.status}`);
  return res.json();
}

export function EmbedBlock({ refId, taskId }: { refId: string; taskId: number }) {
  const [modalOpen, setModalOpen] = useState(false);

  const { data, isLoading, error } = useQuery({
    queryKey: ['embed', taskId, refId],
    queryFn: () => fetchStructuredBlock(taskId, refId),
    staleTime: Infinity,
  });

  if (isLoading) {
    return (
      <div className="bg-slate-50 border border-slate-200 rounded-xl p-4 my-2 max-w-[600px] animate-pulse">
        <div className="h-4 bg-slate-200 rounded w-48 mb-3" />
        <div className="flex gap-3">
          <div className="w-40 h-24 bg-slate-200 rounded" />
          <div className="w-40 h-24 bg-slate-200 rounded" />
        </div>
      </div>
    );
  }

  if (error || !data) return null;

  return (
    <>
      {data.type === 'amazon_products' && (
        <AmazonProductsCard
          data={data.data as AmazonData}
          onExpand={() => setModalOpen(true)}
        />
      )}
      {data.type === 'map_places' && (
        <MapPlacesCard
          data={data.data as MapData}
          onExpand={() => setModalOpen(true)}
        />
      )}
      {data.type === 'x_posts' && (
        <XPostsCard
          data={data.data as XPostData}
          onExpand={() => setModalOpen(true)}
        />
      )}
      {data.type === 'youtube_videos' && (
        <YouTubeVideosCard
          data={data.data as YouTubeData}
          onExpand={() => setModalOpen(true)}
        />
      )}

      <EmbedModal open={modalOpen} onClose={() => setModalOpen(false)}>
        {data.type === 'amazon_products' && (
          <AmazonProductsDetail data={data.data as AmazonData} />
        )}
        {data.type === 'map_places' && (
          <MapPlacesDetail data={data.data as MapData} />
        )}
        {data.type === 'x_posts' && (
          <XPostsDetail data={data.data as XPostData} />
        )}
        {data.type === 'youtube_videos' && (
          <YouTubeVideosDetail data={data.data as YouTubeData} />
        )}
      </EmbedModal>
    </>
  );
}
