'use client';

import { FormControl, FormLabel, Input } from '@chakra-ui/react';
import { useStatsigClient } from '@statsig/react-bindings';
import { observer } from 'mobx-react-lite';
import { useEffect } from 'react';

import { UploadState } from '@/app/(root)/create/sandbox/VideoUploadState';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import {
  DISPLAY_HEIGHT,
  DISPLAY_WIDTH,
} from '@/components/modal/editClipMetadata/constants';
import AuraTag from '@/components/tag/AuraTag';
import TextareaV2 from '@/components/textarea/TextareaV2';
import { PhotoGalleryIcon, TrashIcon } from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip } from '@/state/clipStore';
import { DEFAULT_AURA_URL, MAX_TITLE_CHARS } from '@/utils/constants';

export type EditClipMetadataFormProps = {
  clipId: string;
  editedTitle: string;
  setEditedTitle: (title: string) => void;
  currentActiveClip?: Clip;
  currentImage: any;
  setCurrentImage: (image: any) => void;
  continuedClips: Clip[];
  addedImages: (string | null)[];
  audioUploadClipMetadata?: any;
  currentLyrics: string;
  setCurrentLyrics: (lyrics: string) => void;
  currentCaption?: string;
  setCurrentCaption?: React.Dispatch<React.SetStateAction<string>>;
  showLyricsTextarea?: boolean;
  showDisplayTagsIfNeeded?: boolean;
  selectedVideo?: File | null;
  setSelectedVideo?: (video: File | null) => void;
  setIsAddingVideo?: (isAdding: boolean) => void;
  uploadState?: UploadState;
  displayTags?: string;
  setDisplayTags?: (tags: string) => void;
};
export const EditClipMetadataForm = observer(
  ({
    clipId,
    editedTitle,
    setEditedTitle,
    currentActiveClip,
    currentImage,
    setCurrentImage,
    audioUploadClipMetadata,
    displayTags,
    setDisplayTags,
    currentLyrics,
    setCurrentLyrics,
    currentCaption,
    setCurrentCaption,
    showLyricsTextarea = true,
    showDisplayTagsIfNeeded = true,
    selectedVideo,
    setSelectedVideo,
    setIsAddingVideo,
    uploadState,
  }: EditClipMetadataFormProps) => {
    const statsigClient = useStatsigClient();
    const showCaptionsFeature = statsigClient.checkGate('web-captions');
    const showVideoCoverUploadFeature = statsigClient.checkGate(
      'web-video-cover-upload'
    );

    useEffect(() => {
      setCurrentLyrics?.(currentActiveClip?.metadata?.prompt || '');
    }, [currentActiveClip?.metadata?.prompt]);

    useEffect(() => {
      setCurrentCaption?.(currentActiveClip?.caption || '');
    }, [currentActiveClip?.caption]);

    // Placeholder until we have an onboarding table
    const showNewTag = false;

    const showDisplayTags =
      showDisplayTagsIfNeeded &&
      (currentActiveClip?.major_model_version === 'v4.5' || displayTags);

    const hasVideo =
      !!selectedVideo ||
      (selectedVideo !== null && !!currentActiveClip?.video_cover_url);

    return (
      <div className={'align-start flex flex-col gap-4 md:flex-row'}>
        {(currentActiveClip?.status === 'complete' ||
          audioUploadClipMetadata) && (
          <div className='flex min-w-40 flex-col items-center gap-2'>
            <FormLabel
              fontFamily={'Neue Montreal'}
              alignSelf='flex-start'
              mb={1}
            >
              Cover Art
            </FormLabel>
            <div
              className='relative aspect-9/16 overflow-hidden rounded-lg'
              style={{ height: DISPLAY_HEIGHT }}
            >
              {hasVideo ? (
                <div className='relative'>
                  <video
                    src={
                      selectedVideo
                        ? URL.createObjectURL(selectedVideo)
                        : currentActiveClip?.video_cover_url || ''
                    }
                    controls
                    style={{
                      width: DISPLAY_WIDTH,
                      height: DISPLAY_HEIGHT,
                      objectFit: 'cover',
                    }}
                    controlsList='nodownload nofullscreen noremoteplayback'
                  />
                  {uploadState?.isUploading && (
                    <div className='absolute inset-0 flex items-center justify-center bg-black/70 text-white'>
                      <p>Uploading...</p>
                    </div>
                  )}
                  {uploadState?.isProcessing && (
                    <div className='absolute inset-0 flex items-center justify-center bg-black/70 text-white'>
                      <p>Processing...</p>
                    </div>
                  )}
                </div>
              ) : (
                <ImageWithFallback
                  className='h-full w-full object-cover'
                  alt=''
                  src={currentImage || undefined}
                  fallbackSrc={DEFAULT_AURA_URL}
                />
              )}
              {(currentImage && currentImage !== DEFAULT_AURA_URL) ||
              hasVideo ? (
                <Button
                  className='absolute top-2 right-2'
                  variant={ButtonVariant.Fog}
                  size={ButtonSize.Small}
                  shape={ButtonShape.Pill}
                  onClick={() => {
                    setCurrentImage(null);
                    setSelectedVideo?.(null);
                  }}
                  icon={TrashIcon}
                  aria-label='Remove Cover Art'
                />
              ) : null}
            </div>
            <div className='flex w-full flex-col gap-2'>
              <Button
                onClick={() => {
                  setIsAddingVideo?.(true);
                  logWebUserEvent({
                    actionName: 'SongEditCoverArtClicked',
                    principalObjectType: 'song',
                    principalObjectValue: clipId,
                    context: {
                      clipId,
                      mediaType: 'video',
                    },
                  });
                }}
                icon={PhotoGalleryIcon}
                className='w-full'
              >
                {hasVideo ? 'Replace Video' : 'Add a Video'}
              </Button>
            </div>
          </div>
        )}

        <div className='flex flex-1 flex-col'>
          <FormControl mb={3.5}>
            <FormLabel fontFamily={'Neue Montreal'}>Title</FormLabel>
            <Input
              value={editedTitle || ''}
              fontFamily={'Neue Montreal'}
              maxLength={MAX_TITLE_CHARS}
              onChange={(event) => setEditedTitle(event.target.value)}
              _focus={{
                border: 'solid',
                borderWidth: '0.5px',
                borderColor: '#FAF7F5',
                boxShadow: '0 0 0 0.5px #FAF7F5',
              }}
            />
          </FormControl>

          {showCaptionsFeature && (
            <FormControl mb={3.5}>
              <FormLabel fontFamily={'Neue Montreal'}>
                <span className='flex items-center gap-[3px]'>
                  Caption
                  {showNewTag && (
                    <AuraTag
                      label='New'
                      gradient={
                        'linear-gradient(180deg, #FC7E85 0%, #C862A8 43%, #521B9C 100%)'
                      }
                    />
                  )}
                </span>
              </FormLabel>
              <TextareaV2
                minRows={
                  showVideoCoverUploadFeature && !showDisplayTags ? 2 : 1
                }
                maxRows={
                  showVideoCoverUploadFeature && !showDisplayTags ? 2 : 1
                }
                maxLength={500}
                value={currentCaption || ''}
                resize={true}
                textAreaClassName='pb-2.5'
                onChange={(e) => {
                  const filteredValue = e.target.value.replace(/\n/g, '');
                  setCurrentCaption?.(filteredValue);
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    e.preventDefault();
                  }
                }}
                placeholder={'Add caption'}
              />
            </FormControl>
          )}

          {showDisplayTags && (
            <FormControl mb={3.5}>
              <FormLabel fontFamily={'Neue Montreal'}>
                Displayed Style Summary
              </FormLabel>
              <TextareaV2
                maxRows={2}
                maxLength={100}
                value={displayTags?.slice(0, 100) || ''}
                resize={true}
                textAreaClassName='pb-2.5'
                onChange={(e) => {
                  const filteredValue = e.target.value.replace(/\n/g, '');
                  setDisplayTags?.(filteredValue);
                }}
                placeholder={'Add style summary'}
              />
            </FormControl>
          )}

          {(currentActiveClip?.status === 'complete' ||
            audioUploadClipMetadata) &&
            showLyricsTextarea && (
              <FormControl mb={3.5}>
                <FormLabel fontFamily={'Neue Montreal'}>
                  Displayed Lyrics
                </FormLabel>
                <TextareaV2
                  minRows={
                    showVideoCoverUploadFeature && !showDisplayTags
                      ? 5
                      : showDisplayTags
                        ? 3
                        : 4
                  }
                  maxRows={
                    showVideoCoverUploadFeature && !showDisplayTags
                      ? 5
                      : showDisplayTags
                        ? 3
                        : 4
                  }
                  maxLength={7500}
                  value={currentLyrics}
                  resize={true}
                  textAreaClassName='pb-2.5'
                  onChange={(e) => setCurrentLyrics(e.target.value)}
                  placeholder={'Add lyrics'}
                />
              </FormControl>
            )}
        </div>
      </div>
    );
  }
);

export default EditClipMetadataForm;
