import { useCallback, useState } from 'react';
import Debug from 'debug';

import type { PageSectionComponent } from '../types';
import type { BlockTextProps } from './types';

import Box from '~/src/components/Box';
import OutlineButton from '~/src/components/Button/OutlineButton';
import StarIcon from '~/src/components/Icon/StarIcon';
import InputLabel from '~/src/components/InputLabel';
import MultilineTextInput from '~/src/components/MultilineTextInput';
import SwitchSetting from '~/src/components/Switch/SwitchSetting';
import TextInput from '~/src/components/TextInput';
import useIsEnabled from '~/src/hooks/useIsEnabled';
import { useI18n } from '~/src/lib/i18n';
import { toRgba } from '~/src/lib/utils/color';
import { Features } from '~/src/store/session/types';
import { usePageTheme } from '../../hooks/theme';
import { useEditActions } from '../../ItemPageEdit/useEditActions';
import { EditWrapper } from '../lib/EditWrapper';
import SectionTitle from '../lib/SectionTitle';
import { GenerateTextDialog } from './GenerateTextDialog';
import { resolveText } from './utils';

const debug = Debug('songwhip/BlockTextEdit');

const BlockTextEdit: PageSectionComponent<BlockTextProps> = ({
  layoutData,
  sectionPath,
  title,
  text,
  withShowMore = true,
  ...boxProps
}) => {
  const textResolved = resolveText({ text, layoutData });
  const [textState, setTextState] = useState(textResolved);
  const [isAiDialogOpen, setIsAiDialogOpen] = useState(false);
  const { updateLayoutSection } = useEditActions();
  const pageTheme = usePageTheme();
  const { t } = useI18n();
  const isAiEnabled = useIsEnabled(Features.AI_TEXT_GENERATION);

  // Extract page and artist context
  const { item } = layoutData;
  const pageName = item.name;
  // For artist pages, the artist name is just 'name'. For other items, it's 'artistName'
  const artistName = 'artistName' in item ? item.artistName : item.name;

  // Build context object with available data
  const context = {
    description:
      'description' in item && item.description ? item.description : undefined,
    links:
      'links' in item && item.links
        ? Object.entries(item.links).reduce(
            (acc, [key, value]) => {
              if (value && typeof value === 'string') {
                acc[key] = value;
              }
              return acc;
            },
            {} as Record<string, string>
          )
        : undefined,
    releaseDate:
      'releaseDate' in item && item.releaseDate ? item.releaseDate : undefined,
    type: item.type,
    genres:
      'genres' in item && Array.isArray(item.genres) ? item.genres : undefined,
  };

  return (
    <Box testId="textSectionEdit" {...boxProps}>
      <EditWrapper
        padding="1.6rem 1rem 2rem"
        sectionPath={sectionPath}
        renderSettingsContent={useCallback(() => {
          return (
            <>
              <InputLabel value={t('itemEdit.labels.componentTitle')}>
                <TextInput
                  defaultValue={title}
                  onChange={({ value }) => {
                    updateLayoutSection({
                      sectionPath,

                      changedProps: {
                        title: value,
                      },
                    });
                  }}
                />
              </InputLabel>
              <SwitchSetting
                flexRow
                margin="2.4rem 0 0"
                title={t('itemEdit.labels.showMoreButton')}
                description={t('itemEdit.showMoreButtonHelp', {
                  maxLines: 4,
                })}
                value={withShowMore}
                onChange={(value) => {
                  updateLayoutSection({
                    sectionPath,

                    changedProps: {
                      withShowMore: value,
                    },
                  });
                }}
              />
            </>
          );
        }, [title, withShowMore, updateLayoutSection])}
      >
        <SectionTitle text={title} minHeight="3.5rem" isSticky={false} />
        {isAiEnabled && (
          <Box margin="1rem 0">
            <OutlineButton
              text={t('itemEdit.aiText.openButton')}
              height="3.6rem"
              Icon={StarIcon}
              onClick={() => setIsAiDialogOpen(true)}
            />
          </Box>
        )}
        <MultilineTextInput
          minHeight="15rem"
          fontSize="1.7rem"
          value={textState}
          backgroundColor={pageTheme.backgroundColor}
          borderColor={toRgba(pageTheme.textColor, 0.3)}
          placeholder={t('itemEdit.labels.enterSomeText')}
          onChange={({ value }) => {
            setTextState(value);
          }}
          onInputEnd={({ value }) => {
            debug('on input end', value);

            updateLayoutSection({
              sectionPath,

              changedProps: {
                title,
                text: value,
              },
            });
          }}
        />
      </EditWrapper>
      {isAiEnabled && isAiDialogOpen && (
        <GenerateTextDialog
          onClose={() => setIsAiDialogOpen(false)}
          onApply={(newText) => {
            setTextState(newText);
            updateLayoutSection({
              sectionPath,
              changedProps: { title, text: newText },
            });
            setIsAiDialogOpen(false);
          }}
          pageName={pageName}
          artistName={artistName}
          existingText={textState || undefined}
          context={context}
        />
      )}
    </Box>
  );
};

export default BlockTextEdit;
