/* eslint jsx-a11y/label-has-associated-control: warn */
import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { useModalContext } from '@/context/ModalContext';
import { DownloadIcon } from '@/icons';

import Button, { ButtonVariant } from '../button/Button';
import SpinnerSVG from '../svg/SpinnerSVG';
import Modal from './Modal';
import { ModalTypes } from './constants/ModalTypes';

interface ShareAssetConfig {
  preset_id: string;
  preset_style: string;
  sticker_style: string;
  lyrics_style: string;
}

// Base preset options
const BASE_PRESET_OPTIONS = [
  { id: 'aura', style: 'standard', label: 'Aura Standard' },
  { id: 'aura', style: 'blue', label: 'Aura Blue' },
  { id: 'starfield', style: 'green', label: 'Starfield Green' },
  { id: 'fbm_warp', style: 'pink', label: 'FBM Warp Pink' },
  { id: 'clouds', style: 'standard', label: 'Clouds' },
  { id: 'neon', style: 'pulse', label: 'Neon Pulse' },
  { id: 'synthwave', style: 'scene_v1', label: 'Laser Sunset' },
  { id: 'cover', style: 'image', label: 'Image Cover' },
  { id: 'cover', style: 'video', label: 'Video Cover' },
  // Note: "sliced_screen" is excluded per requirements
];

// Available sticker styles from asset config
const STICKER_STYLES = [
  { id: 'core_lyrics_standard', label: 'Standard (with Lyrics)' },
  { id: 'core_info_standard', label: 'Info Standard' },
  { id: 'leading_info_standard', label: 'Leading Info' },
  { id: 'framed_core_center', label: 'Framed Center' },
  { id: 'framed_core_top', label: 'Framed Top' },
  { id: 'none', label: 'None' },
];

// Lyric style options
const LYRICS_STYLES = [
  { id: 'none', label: 'None' },
  { id: 'lyrics_box', label: 'Lyrics Box' },
  { id: 'lyrics_two_line', label: 'Two Line Lyrics' },
  { id: 'lyrics_three_line', label: 'Three Line Lyrics' },
];

const DownloadShareAssetModal = observer(() => {
  const { clips } = useStores();
  const { closeModal } = useModalContext();
  const clip = clips.selectedShareAssetClip;

  const handleClose = () => {
    closeModal(ModalTypes.DOWNLOAD_SHARE_ASSET);
    clips.clearShareAsset();
  };

  const PRESET_OPTIONS = BASE_PRESET_OPTIONS;

  const [config, setConfig] = useState<ShareAssetConfig>({
    preset_id: 'aura',
    preset_style: 'standard',
    sticker_style: 'core_lyrics_standard',
    lyrics_style: 'lyrics_box',
  });

  const [clipStartTime, setClipStartTime] = useState(0);
  const [clipEndTime, setClipEndTime] = useState(15);
  const [startTimeInput, setStartTimeInput] = useState(
    clipStartTime.toString()
  );
  const [endTimeInput, setEndTimeInput] = useState(clipEndTime.toString());

  // Only core_lyrics_standard should allow lyrics
  const canShowLyrics = config.sticker_style === 'core_lyrics_standard';

  // Reset lyrics style to 'none' when switching to a sticker style that doesn't support lyrics
  useEffect(() => {
    if (!canShowLyrics && config.lyrics_style !== 'none') {
      setConfig((prev) => ({ ...prev, lyrics_style: 'none' }));
    }
  }, [config.sticker_style, config.lyrics_style, canShowLyrics]);

  // Clear state when modal is closed
  useEffect(() => {
    return () => {
      clips.clearShareAsset();
    };
  }, [clips]);

  // Update string inputs when numeric values change externally
  useEffect(() => {
    setStartTimeInput(clipStartTime.toString());
  }, [clipStartTime]);

  useEffect(() => {
    setEndTimeInput(clipEndTime.toString());
  }, [clipEndTime]);

  const handleSubmit = async () => {
    if (!clip) return;
    const payload = {
      asset_config: config,
      clip_start_time: clipStartTime,
      clip_end_time: clipEndTime,
    };

    await clips.createShareAsset(clip, payload);
  };

  const handleDownload = () => {
    if (clips.shareAssetUrl) {
      window.open(clips.shareAssetUrl, '_blank');
    }
  };

  if (!clip) return null;

  return (
    <Modal
      title='Create Shareable Asset'
      onClose={handleClose}
      wrapperClasses='max-h-[580px] mb-4'
      withHorizontalPadding
    >
      <div className='my-4 w-full rounded-lg bg-background-secondary p-4'>
        {!clips.shareAssetId ? (
          <div className='flex flex-col gap-4'>
            <div className='flex flex-col gap-2'>
              <label className='font-medium'>Preset Style</label>
              <div className='flex gap-3'>
                <select
                  className='flex-1 rounded bg-background-tertiary p-2'
                  value={`${config.preset_id}|${config.preset_style}`}
                  onChange={(e) => {
                    const [preset_id, preset_style] = e.target.value.split('|');
                    setConfig({ ...config, preset_id, preset_style });
                  }}
                >
                  {PRESET_OPTIONS.map((preset) => (
                    <option
                      key={`${preset.id}-${preset.style}`}
                      value={`${preset.id}|${preset.style}`}
                    >
                      {preset.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className='flex flex-col gap-2'>
              <label className='font-medium'>Display Options</label>
              <div className='flex gap-3'>
                <select
                  className='flex-1 rounded bg-background-tertiary p-2'
                  value={config.sticker_style}
                  onChange={(e) =>
                    setConfig({ ...config, sticker_style: e.target.value })
                  }
                >
                  {STICKER_STYLES.map((style) => (
                    <option key={style.id} value={style.id}>
                      {style.label}
                    </option>
                  ))}
                </select>
                <select
                  className='flex-1 rounded bg-background-tertiary p-2'
                  value={config.lyrics_style}
                  onChange={(e) =>
                    setConfig({ ...config, lyrics_style: e.target.value })
                  }
                  disabled={!canShowLyrics}
                >
                  {LYRICS_STYLES.map((style) => (
                    <option key={style.id} value={style.id}>
                      {style.label}
                    </option>
                  ))}
                </select>
              </div>
              {!canShowLyrics && (
                <div className='mt-1 text-xs text-gray-400'>
                  Lyrics are only available with the Standard sticker style
                </div>
              )}
            </div>

            <div className='flex flex-col gap-2'>
              <label className='font-medium'>Clip Time Range (seconds)</label>
              <div className='flex gap-3'>
                <div className='flex-1'>
                  <label className='text-sm'>Start</label>
                  <input
                    type='number'
                    className='w-full rounded bg-background-tertiary p-2'
                    value={startTimeInput}
                    onChange={(e) => {
                      setStartTimeInput(e.target.value);
                      if (e.target.value !== '') {
                        const numValue = Number(e.target.value);
                        if (!isNaN(numValue)) {
                          setClipStartTime(numValue);
                        }
                      }
                    }}
                    onBlur={() => {
                      // If empty on blur, reset to 0
                      if (
                        startTimeInput === '' ||
                        isNaN(Number(startTimeInput))
                      ) {
                        setStartTimeInput('0');
                        setClipStartTime(0);
                      }
                    }}
                    min={0}
                    step='any'
                  />
                </div>
                <div className='flex-1'>
                  <label className='text-sm'>End</label>
                  <input
                    type='number'
                    className='w-full rounded bg-background-tertiary p-2'
                    value={endTimeInput}
                    onChange={(e) => {
                      setEndTimeInput(e.target.value);
                      if (e.target.value !== '') {
                        const numValue = Number(e.target.value);
                        if (!isNaN(numValue)) {
                          setClipEndTime(numValue);
                        }
                      }
                    }}
                    onBlur={() => {
                      // If empty on blur, reset to a valid value
                      if (endTimeInput === '' || isNaN(Number(endTimeInput))) {
                        const validValue = Math.max(clipStartTime + 1, 1);
                        setEndTimeInput(validValue.toString());
                        setClipEndTime(validValue);
                      }
                    }}
                    min={clipStartTime + 1}
                    step='any'
                  />
                </div>
              </div>
            </div>

            <Button
              className='mt-2 w-full py-4'
              variant={ButtonVariant.Primary}
              onClick={handleSubmit}
              disabled={clips.pendingShareAssetClip !== null}
              icon={clips.pendingShareAssetClip ? <SpinnerSVG /> : null}
            >
              {clips.pendingShareAssetClip
                ? 'Creating...'
                : 'Create Share Asset'}
            </Button>
          </div>
        ) : (
          <div className='flex flex-col gap-4'>
            <div className='flex items-center justify-center font-medium'>
              {clips.shareAssetStatus === 'rendering' && (
                <div className='flex items-center gap-2'>
                  <SpinnerSVG />
                  <span>Rendering your share asset...</span>
                </div>
              )}
              {clips.shareAssetStatus === 'complete' && (
                <div className='flex items-center gap-2'>
                  <span>Your share asset is ready!</span>
                </div>
              )}
              {clips.shareAssetStatus === 'error' && (
                <div className='flex items-center gap-2 text-accent-error-on-primary'>
                  <span>Error creating share asset</span>
                </div>
              )}
            </div>

            {clips.shareAssetStatus === 'complete' && clips.shareAssetUrl && (
              <Button
                className='mt-2 w-full py-4'
                variant={ButtonVariant.Secondary}
                onClick={handleDownload}
                icon={DownloadIcon}
              >
                Download Share Asset
              </Button>
            )}

            {clips.shareAssetStatus !== 'rendering' && (
              <Button
                className='mt-2 w-full py-4'
                variant={ButtonVariant.Tertiary}
                onClick={() => {
                  clips.clearShareAsset();
                }}
              >
                Create Another
              </Button>
            )}
          </div>
        )}
      </div>
    </Modal>
  );
});

export default DownloadShareAssetModal;
