import { useEffect, useRef, useState } from 'react';

import type { AiGenerateTextRequest } from '~/src/lib/ai/types';
import type { FC } from 'react';

import { toSongwhipApiError } from '~/lib/songwhipApi/songwhipApi';
import Box from '~/src/components/Box';
import OutlineButton from '~/src/components/Button/OutlineButton';
import PrimaryButton from '~/src/components/Button/PrimaryButton';
import DialogBox from '~/src/components/DialogBox';
import { DialogBoxHeader } from '~/src/components/DialogBox/DialogBoxHeader';
import InputLabel from '~/src/components/InputLabel';
import MultilineTextInput from '~/src/components/MultilineTextInput';
import { generateText } from '~/src/lib/ai/generateText';
import { useI18n } from '~/src/lib/i18n';

interface GenerateTextDialogProps {
  onClose: () => void;
  onApply: (text: string) => void;
  pageName: string;
  artistName: string;
  existingText?: string;
  context?: AiGenerateTextRequest['context'];
}

// Parent mounts/unmounts on open/close; each fresh mount resets local state
// via useState initializers. No internal reset needed.
export const GenerateTextDialog: FC<GenerateTextDialogProps> = ({
  onClose,
  onApply,
  pageName,
  artistName,
  existingText,
  context,
}) => {
  const { t } = useI18n();
  const [prompt, setPrompt] = useState('');
  const [mode, setMode] = useState<'replace' | 'refine'>('replace');
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedText, setGeneratedText] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const hasExistingText = Boolean(existingText);

  const isMountedRef = useRef(true);
  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  const handleGenerate = async () => {
    const trimmed = prompt.trim();
    if (!trimmed) return;

    setIsGenerating(true);
    setError(null);

    try {
      const result =
        mode === 'refine' && existingText
          ? await generateText({
              prompt: trimmed,
              pageName,
              artistName,
              mode: 'refine',
              existingText,
              context,
            })
          : await generateText({
              prompt: trimmed,
              pageName,
              artistName,
              mode: 'replace',
              context,
            });

      if (!isMountedRef.current) return;
      setGeneratedText(result.text);
    } catch (err) {
      if (!isMountedRef.current) return;
      const apiError = toSongwhipApiError(err);
      setError(apiError.message || t('itemEdit.aiText.genericError'));
    } finally {
      if (isMountedRef.current) {
        setIsGenerating(false);
      }
    }
  };

  const handleApply = () => {
    if (generatedText) {
      onApply(generatedText);
    }
  };

  return (
    <DialogBox
      testId="generateTextDialog"
      renderHeader={({ close }) => (
        <DialogBoxHeader
          title={t('itemEdit.aiText.dialogTitle')}
          onCloseClick={close}
        />
      )}
      maxHeight="90vh"
      onClose={onClose}
      renderContent={({ paddingX, paddingY }) => (
        <Box padding={`0 ${paddingX} ${paddingY}`} flexColumn gap="2rem">
          {/* Mode selection - only show if there's existing text */}
          {hasExistingText && (
            <Box flexColumn gap="1rem">
              <Box
                style={{
                  fontSize: '1.4rem',
                  fontWeight: 500,
                  color: '#fff',
                }}
              >
                {t('itemEdit.aiText.modeLabel')}
              </Box>
              <Box flexColumn gap="0.75rem">
                <Box
                  onClick={() => setMode('replace')}
                  style={{
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.8rem',
                  }}
                >
                  <Box
                    style={{
                      width: '2rem',
                      height: '2rem',
                      borderRadius: '50%',
                      border: '2px solid #fff',
                      backgroundColor:
                        mode === 'replace' ? '#fff' : 'transparent',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    {mode === 'replace' && (
                      <Box
                        style={{
                          width: '1rem',
                          height: '1rem',
                          borderRadius: '50%',
                          backgroundColor: '#000',
                        }}
                      />
                    )}
                  </Box>
                  <Box style={{ fontSize: '1.5rem', color: '#fff' }}>
                    {t('itemEdit.aiText.modeReplace')}
                  </Box>
                </Box>
                <Box
                  onClick={() => setMode('refine')}
                  style={{
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.8rem',
                  }}
                >
                  <Box
                    style={{
                      width: '2rem',
                      height: '2rem',
                      borderRadius: '50%',
                      border: '2px solid #fff',
                      backgroundColor:
                        mode === 'refine' ? '#fff' : 'transparent',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                  >
                    {mode === 'refine' && (
                      <Box
                        style={{
                          width: '1rem',
                          height: '1rem',
                          borderRadius: '50%',
                          backgroundColor: '#000',
                        }}
                      />
                    )}
                  </Box>
                  <Box style={{ fontSize: '1.5rem', color: '#fff' }}>
                    {t('itemEdit.aiText.modeRefine')}
                  </Box>
                </Box>
              </Box>
            </Box>
          )}

          {/* Prompt input */}
          <InputLabel
            description={t('itemEdit.aiText.contextLabel', {
              pageName,
              artistName,
            })}
          >
            <MultilineTextInput
              placeholder={t('itemEdit.aiText.placeholder')}
              value={prompt}
              onChange={({ value }) => {
                setPrompt(value);
                setError(null);
              }}
              maxLength={500}
            />
          </InputLabel>

          {/* Error display */}
          {error && (
            <Box
              padding="1.2rem"
              style={{
                backgroundColor: 'rgba(255, 0, 0, 0.1)',
                borderRadius: '0.4rem',
                color: '#ff4444',
              }}
            >
              {error}
            </Box>
          )}

          {/* Preview section */}
          {generatedText && (
            <Box flexColumn gap="1rem">
              <Box
                style={{
                  fontSize: '1.4rem',
                  fontWeight: 500,
                  color: '#fff',
                }}
              >
                {t('itemEdit.aiText.previewLabel')}
              </Box>
              <Box
                padding="1.5rem"
                style={{
                  backgroundColor: 'rgba(255, 255, 255, 0.05)',
                  borderRadius: '0.4rem',
                  border: '1px solid rgba(255, 255, 255, 0.1)',
                  fontSize: '1.5rem',
                  lineHeight: '1.6',
                  color: '#fff',
                  whiteSpace: 'pre-wrap',
                  maxHeight: '30rem',
                  overflowY: 'auto',
                }}
              >
                {generatedText}
              </Box>
            </Box>
          )}

          {/* Action buttons */}
          <Box style={{ display: 'flex', flexDirection: 'row', gap: '2.4rem' }}>
            {!generatedText ? (
              <PrimaryButton
                text={t('itemEdit.aiText.generate')}
                height="4.8rem"
                isLoading={isGenerating}
                isDisabled={!prompt.trim() || isGenerating}
                onClick={handleGenerate}
                style={{ flex: 1 }}
              />
            ) : (
              <>
                <OutlineButton
                  text={t('itemEdit.aiText.regenerate')}
                  height="4.8rem"
                  isLoading={isGenerating}
                  isDisabled={!prompt.trim() || isGenerating}
                  onClick={handleGenerate}
                  style={{ flex: 1 }}
                />
                <PrimaryButton
                  text={t('itemEdit.aiText.apply')}
                  height="4.8rem"
                  isDisabled={isGenerating}
                  onClick={handleApply}
                  style={{ flex: 1 }}
                />
              </>
            )}
          </Box>
        </Box>
      )}
    />
  );
};
