import styled from '@emotion/styled';
import { throttle } from 'lodash-es';
import React, {
  memo,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import MentionSuggestions from '@/components/comment/MentionSuggestions';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import Switch from '@/components/switch/Switch';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { useMentionSearch } from '@/hooks/useComments';
import { useContextSelector } from '@/hooks/useContextSelector';
import { CloseIcon, InfoIcon } from '@/icons';
import { isDevOrStaging } from '@/utils/environment';

import CreateFormContext from '../../v2/CreateFormContext';
import CreateCard from './CreateCard';

const ChameleonModeContent = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  color: var(--color-foreground-primary);
`;

const ChameleonModeInfo = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
`;

const ChameleonModeTitle = styled.span`
  font-size: 14px;
  font-weight: 500;
`;

const UserInputContainer = styled.div`
  padding: 0 16px 16px 16px;
`;

const PersonalizeLyricsRow = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  margin-bottom: 12px;
`;

const PersonalizeLyricsLabel = styled.span`
  font-size: 14px;
  font-weight: 500;
  color: var(--color-foreground-primary);
`;

const WarningMessage = styled.div`
  padding: 8px 12px;
  margin-bottom: 12px;
  background-color: var(--color-warning-background, rgba(255, 193, 7, 0.1));
  border: 1px solid var(--color-warning-border, rgba(255, 193, 7, 0.3));
  border-radius: 8px;
  font-size: 13px;
  color: var(--color-warning-foreground, var(--color-foreground-primary));
`;

const Separator = styled.div`
  border-top: 1px solid var(--color-border-primary);
  margin: 12px 0;
`;

const UserInputWrapper = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  isolation: isolate;
`;

const UserInput = styled.input`
  flex: 1;
  padding: 8px 32px 8px 12px;
  font-size: 14px;
  border: 1px solid var(--color-border-primary);
  border-radius: 8px;
  background-color: var(--color-background-primary);
  color: var(--color-foreground-primary);
  outline: none;

  &:focus {
    border-color: var(--color-border-focus);
  }

  &::placeholder {
    color: var(--color-foreground-tertiary);
  }
`;

const ClearButton = styled.button`
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: var(--color-foreground-tertiary);
  opacity: 0.7;

  &:hover {
    opacity: 1;
  }
`;

const SelectedUserTag = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 32px 8px 12px;
  background-color: var(--color-background-secondary);
  border: 1px solid var(--color-border-primary);
  border-radius: 8px;
  font-size: 14px;
  color: var(--color-foreground-primary);
`;

const UserAvatar = styled.img`
  width: 24px;
  height: 24px;
  border-radius: 50%;
  object-fit: cover;
`;

const ChameleonModeCard: React.FC = memo(function ChameleonModeCard() {
  const { session } = useStores();
  const chameleonMode = useContextSelector(
    CreateFormContext,
    (context) =>
      context.state.global.untimedConditions.chameleon?.enabled ?? false
  );
  const targetUser = useContextSelector(
    CreateFormContext,
    (context) =>
      context.state.global.untimedConditions.chameleon?.targetUser ?? null
  );
  const personalizeLyrics = useContextSelector(
    CreateFormContext,
    (context) =>
      context.state.global.untimedConditions.chameleon?.personalizeLyrics ??
      false
  );
  const setChameleonMode = useContextSelector(
    CreateFormContext,
    (context) => context.setChameleonMode
  );
  const setChameleonTargetUser = useContextSelector(
    CreateFormContext,
    (context) => context.setChameleonTargetUser
  );
  const setChameleonPersonalizeLyrics = useContextSelector(
    CreateFormContext,
    (context) => context.setChameleonPersonalizeLyrics
  );

  const [inputValue, setInputValue] = useState('');
  const [mentionQuery, setMentionQuery] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const { suggestedUsers } = useMentionSearch(mentionQuery);

  const updateMentionQuery = useMemo(
    () =>
      throttle((value: string) => {
        // Start searching after @ symbol or if there's any text
        if (value.startsWith('@')) {
          setMentionQuery(':' + value.slice(1));
        } else if (value.length > 0) {
          setMentionQuery(':' + value);
        } else {
          setMentionQuery(null);
        }
      }, 250),
    []
  );

  useEffect(() => {
    return () => {
      updateMentionQuery.cancel();
    };
  }, [updateMentionQuery]);

  const handleInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const value = e.target.value;
      setInputValue(value);
      updateMentionQuery(value);
    },
    [updateMentionQuery]
  );

  const handleUserSelect = useCallback(
    (handle: string, _: string) => {
      // Find the full user info from suggested users
      const selectedUser = suggestedUsers.find((u) => u.handle === handle);
      if (selectedUser) {
        setChameleonTargetUser({
          userId: selectedUser.externalUserId || '',
          handle: selectedUser.handle || handle,
          displayName: selectedUser.displayName,
          avatarImageUrl: selectedUser.avatarImageUrl,
        });
        setInputValue('');
        setMentionQuery(null);
      }
    },
    [suggestedUsers, setChameleonTargetUser]
  );

  const handleClearUser = useCallback(() => {
    setChameleonTargetUser(null);
  }, [setChameleonTargetUser]);

  const handleClearInput = useCallback(() => {
    setInputValue('');
    setMentionQuery(null);
  }, []);

  if (!session.flags?.['use-personalization']) {
    return null;
  }

  return (
    <CreateCard collapsible={false} style={{ overflow: 'visible' }}>
      <ChameleonModeContent>
        <ChameleonModeInfo>
          <ChameleonModeTitle>
            Chameleon Mode
            <ImageWithFallback
              src={
                chameleonMode
                  ? 'https://cdn-o.suno.com/chameleon.png'
                  : 'https://cdn-o.suno.com/chameleon-disabled.png'
              }
              alt='Chameleon'
              style={{
                display: 'inline-block',
                height: 24,
                marginLeft: 8,
                verticalAlign: 'middle',
              }}
              fallbackSrc='https://cdn-o.suno.com/chameleon-disabled.png'
            />
          </ChameleonModeTitle>
          <Tooltip label={'Adapt to your style'}>
            <InfoIcon className='h-4 w-4 opacity-50' />
          </Tooltip>
        </ChameleonModeInfo>
        <Switch
          checked={chameleonMode}
          onChange={() => setChameleonMode(!chameleonMode)}
          small
        />
      </ChameleonModeContent>
      {chameleonMode && (
        <UserInputContainer>
          <PersonalizeLyricsRow>
            <PersonalizeLyricsLabel>Personalize Lyrics</PersonalizeLyricsLabel>
            <Switch
              checked={personalizeLyrics}
              onChange={() => setChameleonPersonalizeLyrics(!personalizeLyrics)}
              small
            />
          </PersonalizeLyricsRow>
          {personalizeLyrics && (
            <WarningMessage>
              Warning: Your lyrics will be overwritten by the personalized
              lyrics. Displayed lyrics may not be accurate.
            </WarningMessage>
          )}
          {isDevOrStaging && (
            <>
              <Separator />
              {targetUser ? (
                <SelectedUserTag>
                  {targetUser.avatarImageUrl && (
                    <UserAvatar
                      src={targetUser.avatarImageUrl}
                      alt={targetUser.displayName || targetUser.handle}
                    />
                  )}
                  <span>
                    {targetUser.displayName || `@${targetUser.handle}`}
                  </span>
                  <ClearButton onClick={handleClearUser} type='button'>
                    <CloseIcon className='h-4 w-4' />
                  </ClearButton>
                </SelectedUserTag>
              ) : (
                <UserInputWrapper>
                  <UserInput
                    ref={inputRef}
                    type='text'
                    placeholder='Search for a user to adapt to their style...'
                    value={inputValue}
                    onChange={handleInputChange}
                  />
                  {inputValue && (
                    <ClearButton onClick={handleClearInput} type='button'>
                      <CloseIcon className='h-4 w-4' />
                    </ClearButton>
                  )}
                  {mentionQuery && suggestedUsers.length > 0 && (
                    <div
                      className='absolute top-full right-0 left-0 mt-1'
                      style={{ zIndex: 10001 }}
                    >
                      <MentionSuggestions
                        className='border border-border-primary'
                        query={mentionQuery}
                        onSelect={handleUserSelect}
                        onSuggestion={() => {}}
                      />
                    </div>
                  )}
                </UserInputWrapper>
              )}
            </>
          )}
        </UserInputContainer>
      )}
    </CreateCard>
  );
});

export default ChameleonModeCard;
