'use client';

import { useCallback, useMemo, useState } from 'react';

import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ModalHeader from '@/components/modal/publishSong/ModalHeader';
import PublishModalFooter from '@/components/modal/publishSong/PublishModalFooter';
import { toast } from '@/components/toast/Toast';
import useLogOnMount from '@/hooks/useLogOnMount';
import type { GenerationCarouselState } from '@/hooks/useSongModal';
import { ChevronLeftIcon, ChevronRightIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';

import { GenerationHistoryItem } from './GenerationHistoryItem';
import type {
  FavoriteResponse,
  HistoryBatchItem,
  MediaType,
  ToggleFavoriteHandler,
} from './generationHistoryTypes';
import { useSaveAsCover } from './useSaveAsCover';

interface GenerationCarouselModalContentProps {
  onClose: () => void;
  onBack: () => void;
  onBackToMain: () => void;
  initialState: GenerationCarouselState;
  clipId: string;
}

export const GenerationCarouselModalContent = ({
  onClose,
  onBack,
  onBackToMain,
  initialState,
  clipId,
}: GenerationCarouselModalContentProps) => {
  const { saveAsImageCover, saveAsVideoCover, toggleFavorite } =
    useSaveAsCover();
  const [carouselItems, setCarouselItems] = useState(initialState.items);
  const [currentIndex, setCurrentIndex] = useState(initialState.initialIndex);
  const currentItem = carouselItems[currentIndex];

  // Track carousel modal view with initial item context
  useLogOnMount({
    actionName: 'GenerateCoverArtDetailModalViewed',
    principalObjectType: 'clip',
    principalObjectValue: clipId,
    context: {
      generationType: currentItem.type,
      videoId: currentItem.type === 'video' ? currentItem.id : undefined,
      imageId: currentItem.type === 'image' ? currentItem.id : undefined,
    },
  });

  const canGoBack = currentIndex > 0;
  const canGoForward = currentIndex < carouselItems.length - 1;

  const handlePrevious = () => {
    if (canGoBack) {
      setCurrentIndex(currentIndex - 1);
    }
  };

  const handleNext = () => {
    if (canGoForward) {
      setCurrentIndex(currentIndex + 1);
    }
  };

  const handleToggleFavorite: ToggleFavoriteHandler = useCallback(
    async (
      entityType: MediaType,
      entityId: string,
      currentIsLiked: boolean,
      clipId: string
    ): Promise<FavoriteResponse> => {
      try {
        const result = await toggleFavorite(
          entityType,
          entityId,
          currentIsLiked,
          clipId
        );
        // Update local state to reflect the new liked status
        setCarouselItems((prev) =>
          prev.map((item) =>
            item.id === entityId ? { ...item, isLiked: result.isLiked } : item
          )
        );
        return result;
      } catch (error) {
        const err = error as Error;
        toast({
          title: 'Failed to toggle favorite',
          description: err.message,
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
        return { success: false, isLiked: currentIsLiked };
      }
    },
    [toggleFavorite]
  );

  const handleSaveMediaAsCover = useCallback(async () => {
    // Log set as cover event
    logWebUserEvent({
      actionName: 'GenerateCoverArtSetAsCoverClicked',
      principalObjectType: 'clip',
      principalObjectValue: clipId,
      context: {
        generationType: currentItem.type,
        videoId: currentItem.type === 'video' ? currentItem.id : undefined,
        imageId: currentItem.type === 'image' ? currentItem.id : undefined,
      },
    });

    if (currentItem.type === 'image') {
      try {
        await saveAsImageCover.mutateAsync({
          clipId,
          imageUrl: currentItem.url,
        });
        toast({
          title: 'Your song details have been updated.',
          status: 'info',
          duration: 5000,
          isClosable: true,
        });
        // Navigate to main Edit Song Details screen after saving
        onBackToMain();
      } catch (error) {
        const err = error as Error;
        toast({
          title: 'Failed to save image cover',
          description: err.message,
          status: 'error',
          duration: 5000,
          isClosable: true,
        });
      }
      return;
    }

    if (!currentItem.videoUploadId) {
      toast({
        title: 'Failed to save video cover',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      return;
    }

    try {
      await saveAsVideoCover.mutateAsync({
        clipId,
        videoCoverUploadId: currentItem.videoUploadId,
      });
      toast({
        title: 'Your song details have been updated.',
        status: 'info',
        duration: 5000,
        isClosable: true,
      });
      // Navigate to main Edit Song Details screen after saving
      onBackToMain();
    } catch (error) {
      const err = error as Error;
      toast({
        title: 'Failed to save video cover',
        description: err.message,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    }
  }, [currentItem, clipId, saveAsImageCover, saveAsVideoCover, onBackToMain]);

  const currentHistoryItem: HistoryBatchItem = useMemo(
    () => ({
      id: currentItem.id,
      clipId: currentItem.clipId,
      type: currentItem.type,
      url: currentItem.url,
      status: 'complete' as const,
      isLiked: currentItem.isLiked,
    }),
    [currentItem]
  );

  return (
    <div className='flex h-full max-h-[80vh] w-full flex-col overflow-hidden'>
      <ModalHeader
        title={currentItem.title || 'Generated Content'}
        subtitle={new Date(currentItem.createdAt).toLocaleString()}
        onBack={onBack}
        onClose={onClose}
        titleClassName='font-sans text-xl font-medium'
        titleGroupClassName='items-center'
      />

      <div className='flex flex-1 flex-col items-center gap-6 overflow-y-auto px-6 py-2'>
        {/* Main carousel view with navigation */}
        <div className='flex w-full shrink-0 items-center justify-between'>
          {/* Left navigation button */}
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            size={ButtonSize.Medium}
            icon={ChevronLeftIcon}
            iconOnly
            onClick={handlePrevious}
            disabled={!canGoBack}
            aria-label='Previous'
            className={!canGoBack ? 'opacity-50' : ''}
          />

          {/* Display the current item card - larger size */}
          <GenerationHistoryItem
            item={currentHistoryItem}
            onToggleFavorite={handleToggleFavorite}
            className='h-[350px] w-[204px]'
          />

          {/* Right navigation button */}
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            size={ButtonSize.Medium}
            icon={ChevronRightIcon}
            iconOnly
            onClick={handleNext}
            disabled={!canGoForward}
            aria-label='Next'
          />
        </div>

        {/* Prompt box - wider to match Figma */}
        <div className='w-full max-w-lg shrink-0'>
          <div className='flex flex-col gap-1 rounded-2xl border border-border-secondary bg-background-secondary p-4'>
            <span className='text-xs text-foreground-inactive'>Prompt</span>
            <p className='min-h-[3rem] overflow-y-scroll text-sm text-foreground-primary'>
              {currentItem.prompt || 'No Prompt Used'}
            </p>
          </div>
        </div>
      </div>

      <PublishModalFooter>
        <div className='flex w-full items-center justify-end'>
          <Button
            variant={ButtonVariant.Primary}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            onClick={handleSaveMediaAsCover}
          >
            Save as {currentItem.type === 'video' ? 'Video' : 'Image'} Cover
          </Button>
        </div>
      </PublishModalFooter>
    </div>
  );
};

export default GenerationCarouselModalContent;
