import { useState } from 'react';
import axios from 'axios';
import CloseButtonIcon from '@/assets/icons/CloseButtonIcon';
import DotLoader from '@/Components/ui/dotloader';
import SequentialFadeWrapper from '@/Components/Transition/SequentialFadeWrapper';
import TeacherLayoutWithProviders from '@/Layouts/TeacherLayout';
import { useNavigationContext } from '@/Contexts/NavigationContext';
import CloseIconButton from '@/Components/CloseIconButton';
import PrimaryActionButton from '@/Components/PrimaryActionButton';

interface WordFocusProps {
  word_focus?: string;
}

export default function WordFocus({ word_focus: initialWordFocus = '' }: WordFocusProps) {
  const { navigate } = useNavigationContext();
  const [words, setWords] = useState(initialWordFocus);
  const [isContentFocused, setIsContentFocused] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [currentStep, setCurrentStep] = useState<'default' | 'enabled' | 'disabled'>('default');
  const [successType, setSuccessType] = useState<'enabled' | 'disabled' | null>(null);
  const [isCloseHovered, setIsCloseHovered] = useState(false);
  const [isCloseClicked, setIsCloseClicked] = useState(false);

  const isDirty = words.trim() !== initialWordFocus.trim();

  const footerKey = isProcessing ? 'processing' : 'default';

  const handleSave = () => {
    if (isProcessing || !isDirty) return;
    setIsProcessing(true);
    const startTime = Date.now();
    const MIN_PROCESSING_MS = 2000;

    axios
      .post('/stories/word-focus', { words })
      .then((response) => {
        setTimeout(() => {
          const nextStep = words.trim() === '' ? 'disabled' : 'enabled';
          setSuccessType(nextStep);
          setCurrentStep(nextStep);
          setIsProcessing(false);
        }, 4000);
      })
      .catch(() => {
        setIsProcessing(false);
      });
  };

  const handleClose = () => {
    if (typeof window !== 'undefined') {
      window.sessionStorage.removeItem('teacherStoriesState');
      window.sessionStorage.removeItem('teacherStoriesScrollTop');
    }
    navigate('/stories', { scope: ['subContent'], duration: 400 });
  };

  return (
    <SequentialFadeWrapper transitionKey={currentStep} className="flex h-full flex-col">
      {currentStep === 'default' ? (
        <>
          {/* Header */}
          <div className="m-0 mb-[8px] flex items-center justify-between p-0">
            <h1 className="flex -translate-y-[1px] items-center font-readingful text-[2.4rem] font-bold leading-none text-[#6F8AE2]">
              Word Focus
            </h1>
            <button
              onClick={handleClose}
              onMouseEnter={() => setIsCloseHovered(true)}
              onMouseLeave={() => {
                setIsCloseHovered(false);
                setIsCloseClicked(false);
              }}
              onMouseDown={() => setIsCloseClicked(true)}
              onMouseUp={() => setIsCloseClicked(false)}
              className="m-0 p-0"
            >
              <CloseButtonIcon
                className="m-0 h-[24px] w-[24px] p-0 transition duration-150"
                fill={isCloseClicked ? '#E2E8F780' : isCloseHovered ? '#E2E8F7BF' : '#E2E8F7'}
              />
            </button>
          </div>
          <p className="mb-[15px] font-readingful text-[2.0rem] font-bold text-[#B7C7F7]">
            Set a list of words to prioritize.
          </p>
          {/* Controlled textarea */}
          <textarea
            value={words}
            onChange={(e) => setWords(e.target.value.substring(0, 170))}
            onFocus={() => setIsContentFocused(true)}
            onBlur={() => setIsContentFocused(false)}
            placeholder={isContentFocused ? '' : 'cat, bat, sat, etc...'}
            maxLength={170}
            spellCheck={false}
            className="scrollbar-hide mb-[15px] w-[550px] h-[100px] resize-none rounded-[24px] border-none bg-[#ebf0fc] px-[20px] py-[18px] font-readingful text-[18px] leading-[1.15] text-[#576082] outline-none duration-200 placeholder:text-[1.8rem] placeholder:font-bold placeholder:tracking-tighter placeholder:text-[#9BA9C9] focus:border-none focus:border-transparent focus:outline-none focus:ring-0 focus:ring-transparent focus-visible:border-none focus-visible:border-transparent focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-transparent"
          />
          {/* Instructional text */}
          <p className="font-readmore text-[1.6rem] leading-tight text-[#576082]">
            Comma separated, list any phonetic, spelling, vocab, or sight
            <br />words for your students to focus on reading in real time.
          </p>

          {/* Footer */}
          <div className="absolute bottom-0 left-0 w-full flex items-end justify-between h-[50px]">
            <SequentialFadeWrapper
              transitionKey={isProcessing}
              duration={300}
              className="translate-y-[5px] font-readmore text-[1.6rem] text-[#BFC6DD]"
            >
              {isProcessing ? (
                <span>Updating word focus list...</span>
              ) : (
                <span>170 characters max.</span>
              )}
            </SequentialFadeWrapper>

            <SequentialFadeWrapper
              transitionKey={footerKey}
              duration={300}
              className="self-end"
            >
              {isProcessing ? (
                <DotLoader dotColor="#85A8FF" size="xl" />
              ) : (
                <button
                  disabled={!isDirty}
                  onClick={handleSave}
                  className="flex h-[50px] w-[90px] cursor-pointer items-center justify-center rounded-full bg-[#6c96ff] font-readingful text-[2.2rem] leading-none text-white transition-opacity duration-150 hover:opacity-75 active:opacity-50 disabled:cursor-default disabled:opacity-50"
                >
                  Save
                </button>
              )}
            </SequentialFadeWrapper>
          </div>
        </>
      ) : currentStep === 'enabled' ? (
        <div className="flex flex-1 flex-col">
          <div className="mb-[8px] flex items-center justify-between p-0">
            <h1 className="flex translate-y-[-1px] items-center font-readingful text-[2.4rem] font-bold leading-none text-[#6F8AE2]">
              Success!
            </h1>
            <CloseIconButton onClick={handleClose} />
          </div>
          <p className="mb-[11px]  font-readingful text-[2.0rem] font-bold text-[#B7C7F7]">
            Your word list has been set and enabled.
          </p>
          <p className="max-w-[600px] font-readmore text-[1.6rem] leading-tight text-[#576082]">
            The custom word list you created is now active. Upon sign in, stories and  <br/>
            articles that have the most prevalent use of this word set will be prioritized <br/>
            for your students ahead of those that include them less frequently. This can <br/>
            be highly advantageous if they are currently studying said terms as part <br/>
            of phonetic, spelling, vocabulary, or sight word instruction.
          </p>
          <div className="mt-auto flex items-end justify-between">
            <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
              This list of priority words will remain active until disabled.
            </p>
            <PrimaryActionButton widthClass="w-[96px]" onClick={handleClose}>
              Close
            </PrimaryActionButton>
          </div>
        </div>
      ) : (
        <div className="flex flex-1 flex-col">
          <div className="mb-[8px] flex items-center justify-between p-0">
            <h1 className="flex translate-y-[-1px] items-center font-readingful text-[2.4rem] font-bold leading-none text-[#6F8AE2]">
              Success!
            </h1>
            <CloseIconButton onClick={handleClose} />
          </div>
          <p className="mb-[11px]  font-readingful text-[2.0rem] font-bold text-[#B7C7F7]">
            Your word list has been disabled.
          </p>
          <p className="max-w-[600px] font-readmore text-[1.6rem] leading-tight text-[#576082]">
           The previously set custom word list is no longer active. This means that, <br/>
           upon sign in, text passages containing the most prevalent use of said words <br/>
           will no longer be prioritized for serving to your students, ahead of text that  <br/>
           does not include them. You may set a new priority word list in the future by <br/>
           revisiting the “Word Focus” tool at your convenience.
          </p>
          <div className="mt-auto flex items-end justify-between">
            <p className="h-[22px] translate-y-[7px] content-end font-readmore text-[16px] leading-none text-[#BFC6DD]">
              Your students are not currently being shown word&ndash;prioritized text.
            </p>
            <PrimaryActionButton widthClass="w-[96px]" onClick={handleClose}>
              Close
            </PrimaryActionButton>
          </div>
        </div>
      )}
    </SequentialFadeWrapper>
  );
}

WordFocus.layout = (page: React.ReactElement) => (
  <TeacherLayoutWithProviders>{page}</TeacherLayoutWithProviders>
);
