import { useQuery } from '@tanstack/react-query';
import { useCallback, useState } from 'react';

import { useContextSelector } from '@/hooks/useContextSelector';
import { ChevronLeftIcon, ChevronRightIcon } from '@/icons';
import { useApiClient } from '@/lib/apiClient';

import { StudioProjectManagementContext } from './StudioProjectManagementContext';
import StudioVersionsTimeline from './StudioVersionsTimeline';

interface StudioVersionsPanelProps {
  onClose: () => void;
  onPreviewVersion?: (versionId: string, state: any) => void;
  onRestoreVersion?: (versionId: string, state: any) => void;
}

export default function StudioVersionsPanel({
  onClose,
  onPreviewVersion,
  onRestoreVersion,
}: StudioVersionsPanelProps) {
  const [currentDateIndex, setCurrentDateIndex] = useState(0);
  const apiClient = useApiClient();

  const projectId = useContextSelector(
    StudioProjectManagementContext,
    (context) => context.loadedProject?.id
  );

  // Fetch revision days
  const { data: versionsResponse, isLoading: isLoadingVersions } = useQuery({
    queryKey: ['studio-versions', projectId],
    queryFn: async () => {
      if (!projectId) return null;
      try {
        const response = await apiClient.GET(
          '/api/studio/{project_id}/versions',
          {
            params: {
              path: { project_id: projectId },
              query: { return_days_only: true },
            },
          }
        );
        return response.data;
      } catch (error) {
        console.error('❌ API call failed:', error);
        throw error;
      }
    },
    enabled: !!projectId,
    staleTime: 0,
    refetchOnMount: true,
    refetchOnWindowFocus: false,
  });

  const revisionDays = (versionsResponse?.days || []).sort(
    (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
  );
  const currentDate = revisionDays[currentDateIndex];

  const handlePreviousDate = useCallback(() => {
    if (currentDateIndex > 0) {
      setCurrentDateIndex((prev) => prev - 1);
    }
  }, [currentDateIndex]);

  const handleNextDate = useCallback(() => {
    if (revisionDays && currentDateIndex < revisionDays.length - 1) {
      setCurrentDateIndex((prev) => prev + 1);
    }
  }, [currentDateIndex, revisionDays]);

  return (
    <div className='flex h-full flex-col border-r border-border-primary bg-background-primary p-4'>
      <div className='mb-2 flex items-center justify-between'>
        <h3 className='text-left font-medium text-foreground-primary'>
          History
        </h3>
        <button
          onClick={onClose}
          className='text-lg leading-none text-foreground-secondary hover:text-foreground-primary'
        >
          ×
        </button>
      </div>
      <p className='mb-4 text-sm text-foreground-secondary'>
        Projects are saved automatically
      </p>
      <div className='mb-4 border-b border-border-primary'></div>

      {isLoadingVersions ? (
        <div className='text-sm text-foreground-secondary'>Loading...</div>
      ) : revisionDays.length > 0 ? (
        <div className='flex min-h-0 flex-1 flex-col'>
          {/* Date navigation */}
          <div className='mb-4 flex items-center justify-between'>
            <button
              onClick={handlePreviousDate}
              disabled={currentDateIndex === 0}
              className='p-1 text-foreground-secondary hover:text-foreground-primary disabled:cursor-not-allowed disabled:opacity-30'
            >
              <ChevronLeftIcon className='h-4 w-4' />
            </button>
            <div className='text-sm font-medium text-foreground-primary'>
              {currentDate
                ? new Date(currentDate.date).toLocaleDateString()
                : 'No date'}
            </div>
            <button
              onClick={handleNextDate}
              disabled={currentDateIndex >= revisionDays.length - 1}
              className='p-1 text-foreground-secondary hover:text-foreground-primary disabled:cursor-not-allowed disabled:opacity-30'
            >
              <ChevronRightIcon className='h-4 w-4' />
            </button>
          </div>

          {/* Version details - Timeline style */}
          <div className='flex-1 overflow-y-auto'>
            {currentDate ? (
              <StudioVersionsTimeline
                selectedDate={currentDate.date}
                onPreviewVersion={onPreviewVersion}
                onRestoreVersion={onRestoreVersion}
              />
            ) : (
              <div className='text-sm text-foreground-secondary'>
                No date selected
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className='text-sm text-foreground-secondary'>
          No revisions found
        </div>
      )}
    </div>
  );
}
