import {
  Checkbox,
  Divider,
  Flex,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalOverlay,
  Stack,
} from '@chakra-ui/react';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { useModalContext } from '@/context/ModalContext';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip, getFeedbackReasons } from '@/state/clipStore';

import Button, { ButtonVariant } from '../button/Button';
import CloseButton from '../button/CloseButton';

const ClipFeedbackModal: React.FC = observer(() => {
  const { clips } = useStores();
  const { closeModal, getModalData, getModalSource } = useModalContext();

  const modalData = getModalData(ModalTypes.CLIP_FEEDBACK);
  const source = getModalSource(ModalTypes.CLIP_FEEDBACK);
  const clipId = modalData?.clipId;
  const clip = clipId ? (clips.getClipById(clipId) as Clip) : undefined;

  const [feedback, setFeedback] = useState({
    goodQuality: false,
    badPoorAudio: false,
    badNoFollowLyrics: false,
    badNoFollowStyle: false,
    badStructure: false,
    other: false,
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target;

    if (name === 'goodQuality') {
      setFeedback({
        goodQuality: checked,
        badPoorAudio: false,
        badNoFollowLyrics: false,
        badNoFollowStyle: false,
        badStructure: false,
        other: false,
      });
    } else {
      setFeedback((prev) => ({
        ...prev,
        [name]: checked,
        goodQuality: false,
      }));
    }
  };

  const getCheckboxColor = (name: string) => {
    if (
      name === 'goodQuality' &&
      (feedback.badPoorAudio ||
        feedback.badNoFollowLyrics ||
        feedback.badNoFollowStyle ||
        feedback.badStructure ||
        feedback.other)
    ) {
      return 'rgba(255, 255, 255, 0.3)';
    } else if (name !== 'goodQuality' && feedback.goodQuality) {
      return 'rgba(255, 255, 255, 0.3)';
    }
    return 'white';
  };

  const handleSubmit = async () => {
    const reasons = [];
    if (feedback.goodQuality) reasons.push('good_quality');
    if (feedback.badPoorAudio) reasons.push('bad_poor_audio_quality');
    if (feedback.badNoFollowLyrics) reasons.push('bad_no_follow_lyrics');
    if (feedback.badNoFollowStyle) reasons.push('bad_no_follow_style');
    if (feedback.badStructure) reasons.push('bad_song_structure');
    if (feedback.other) reasons.push('other');

    try {
      await clips.feedbackClip(clipId || '', reasons.join(','));
      clips.setFeedbackGivenForClip(clipId, true);

      logWebUserEvent({
        actionName: 'ClipFeedbackModalSubmitted',
        context: {
          clipId: clipId || '',
          reasons: reasons.join(','),
          source: source,
        },
      });
    } catch (error) {
      console.error('Failed to submit feedback:', error);
      return;
    }
    closeModal(ModalTypes.CLIP_FEEDBACK);
  };

  const handleRemoveFeedback = async () => {
    try {
      await clips.feedbackClip(clipId || '', '');
      setFeedback({
        goodQuality: false,
        badPoorAudio: false,
        badNoFollowLyrics: false,
        badNoFollowStyle: false,
        badStructure: false,
        other: false,
      });
      clips.setFeedbackGivenForClip(clipId, false);
    } catch (error) {
      console.error('Failed to remove feedback:', error);
      return;
    }
    closeModal(ModalTypes.CLIP_FEEDBACK);
  };

  useEffect(() => {
    if (clip) {
      const feedbackReasons = getFeedbackReasons(clip);
      setFeedback({
        goodQuality: feedbackReasons.includes('good_quality'),
        badPoorAudio: feedbackReasons.includes('bad_poor_audio_quality'),
        badNoFollowLyrics: feedbackReasons.includes('bad_no_follow_lyrics'),
        badNoFollowStyle: feedbackReasons.includes('bad_no_follow_style'),
        badStructure: feedbackReasons.includes('bad_song_structure'),
        other: feedbackReasons.includes('other'),
      });

      logWebUserEvent({
        actionName: 'ClipFeedbackModalOpened',
        context: {
          clipId: clipId || '',
          source: source,
        },
      });
    }
  }, [clip, clipId, source]);

  const handleClose = () => {
    logWebUserEvent({
      actionName: 'ClipFeedbackModalClosed',
      context: {
        clipId: clipId || '',
        source: source,
      },
    });
    closeModal(ModalTypes.CLIP_FEEDBACK);
  };

  return (
    <Modal isOpen={true} onClose={handleClose} isCentered>
      <ModalOverlay />
      <ModalContent
        bg='var(--color-background-primary)'
        color='var(--color-foreground-primary)'
        borderRadius='32px'
      >
        <Flex justifyContent='space-between' alignItems='center' px={3}>
          <span className='py-8 pl-4 font-serif text-2xl'>
            How is the quality of this{' '}
            {clip?.metadata?.history ? 'clip' : 'song'}?
          </span>
          <Flex className='-mt-10'>
            <CloseButton onClick={handleClose} />
          </Flex>
        </Flex>
        <ModalBody>
          <Stack spacing={3}>
            <Checkbox
              name='goodQuality'
              isChecked={feedback.goodQuality}
              onChange={handleChange}
              color={getCheckboxColor('goodQuality')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Great audio quality and song structure
            </Checkbox>
            <Divider />
            <Checkbox
              name='badPoorAudio'
              isChecked={feedback.badPoorAudio}
              onChange={handleChange}
              color={getCheckboxColor('badPoorAudio')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Poor audio/vocal quality
            </Checkbox>
            <Checkbox
              name='badNoFollowLyrics'
              isChecked={feedback.badNoFollowLyrics}
              onChange={handleChange}
              color={getCheckboxColor('badNoFollowLyrics')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Incorrect pronunciation of words
            </Checkbox>
            <Checkbox
              name='badNoFollowStyle'
              isChecked={feedback.badNoFollowStyle}
              onChange={handleChange}
              color={getCheckboxColor('badNoFollowStyle')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Does not adhere to prompt instructions
            </Checkbox>
            <Checkbox
              name='badStructure'
              isChecked={feedback.badStructure}
              onChange={handleChange}
              color={getCheckboxColor('badStructure')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Poor song structure
            </Checkbox>
            <Checkbox
              name='other'
              isChecked={feedback.other}
              onChange={handleChange}
              color={getCheckboxColor('other')}
              colorScheme='gray'
              fontFamily={'Neue Montreal'}
            >
              Other
            </Checkbox>
          </Stack>
        </ModalBody>
        <ModalFooter alignItems={'flex-end'} gap={2}>
          <Button onClick={handleRemoveFeedback}>Clear Feedback</Button>
          <Button variant={ButtonVariant.Primary} onClick={handleSubmit}>
            Submit Feedback
          </Button>
        </ModalFooter>
      </ModalContent>
    </Modal>
  );
});

export default ClipFeedbackModal;
