import React, { useState, useEffect } from 'react';
import Select, {
  components,
  type DropdownIndicatorProps,
  type ControlProps,
  type GroupBase,
  type SingleValue,
} from 'react-select';
import { post } from '../utilities/fetcher.js';
import { RotateCw } from 'lucide-react';
import Lightbulb from './Lightbulb.js';
import Button from '../components/Button.js';
import useSWRImmutable from 'swr/immutable';
import Loading from '../components/Loading.js';
import type { OptionType } from '../utilities/types.js';
import FormIndicator from './FormIndicator.js';
import FormLabel from './FormLabel.js';
import './CreateTitle.css';

export default function CreateTitle({
  accountId,
  draftId,
  brand = '',
  setBrand = (_) => {},
  text = '',
  setText = (_) => {},
}: {
  accountId: string;
  draftId: string;
  brand?: string;
  setBrand?: (_: string) => void;
  text?: string;
  setText?: (_: string) => void;
}) {
  const [menuIsOpen, setMenuIsOpen] = useState(false);

  const minRecommendedCharacters = 50;
  const maxRecommendedCharacters = 61;

  useEffect(() => {
    if (menuIsOpen) {
      mutate(undefined, { revalidate: true });
    }
  }, [menuIsOpen]);

  const { data: dataValidateKeywords, mutate: mutateValidateKeywords } = useSWRImmutable(
    text && draftId
      ? [
          `/conductor/proxy/v3/${accountId}/drafts/${draftId}/validate-keywords/content-guidance`,
          {
            title: text,
          },
        ]
      : null,
    post,
    { fallbackData: [] },
  );
  // Debounce and call mutate when value stabilises.
  useEffect(() => {
    if (text) {
      const timer = setTimeout(() => {
        mutateValidateKeywords();
      }, 500); // Wait 500ms after user stops typing

      return () => {
        clearTimeout(timer);
      };
    }
  }, [text]);
  const titleAnalysis = dataValidateKeywords.filter(
    (item: { type: string }) => item.type === 'HTML_TITLE_COMMON',
  );
  const topicValid = !!titleAnalysis.filter((item: { details: boolean }) =>
    Object.values(item.details).includes(true),
  ).length;

  const { data, isLoading, mutate } = useSWRImmutable(
    [
      `/conductor/proxy/v3/title-tag/content-generation?draft_id=${draftId}`,
      {
        max_characters: maxRecommendedCharacters,
        brand_name: brand,
      },
    ],
    post,
    { fallbackData: { titles: [] } },
  );
  const options =
    data?.titles?.map((title: string) => ({
      value: title,
      label: title,
    })) || [];

  const DropdownIndicator = (
    props: DropdownIndicatorProps<OptionType, boolean, GroupBase<OptionType>>,
  ) => {
    return (
      <components.DropdownIndicator {...props}>
        <Lightbulb />
      </components.DropdownIndicator>
    );
  };

  const Control = ({ children, ...props }: ControlProps<OptionType>) => {
    if (menuIsOpen) {
      return;
    }
    return <components.Control {...props}>{children}</components.Control>;
  };

  return (
    <div className="create-title">
      <div className="create-title__header">
        <FormLabel htmlFor="title-tag">Title tag</FormLabel>
        <div className="create-title__topic">
          <FormIndicator value={titleAnalysis.length ? text : ''} valid={topicValid} />
          Topic
        </div>
        <div
          className="create-title__length"
          title={
            text.length >= minRecommendedCharacters && text.length <= maxRecommendedCharacters
              ? ''
              : 'Title tag falls short of length guidelines.\n' +
                '\n' +
                `Keep your title tag between ${minRecommendedCharacters}-${maxRecommendedCharacters} characters.`
          }
        >
          <FormIndicator
            value={text}
            valid={
              text.length >= minRecommendedCharacters && text.length <= maxRecommendedCharacters
            }
          />
          Length
        </div>
      </div>
      <div className={`create-title__form ${menuIsOpen ? 'create-title__form--is-open' : ''}`}>
        <Select<OptionType, false>
          options={options}
          isLoading={isLoading}
          loadingMessage={() => <Loading />}
          onChange={(selected: SingleValue<OptionType>) => setText(selected ? selected.value : '')}
          isSearchable={false}
          components={{ DropdownIndicator, Control }}
          menuIsOpen={menuIsOpen}
          onMenuOpen={() => setMenuIsOpen(true)}
          onMenuClose={() => setMenuIsOpen(false)}
          className="create-title__select"
          classNamePrefix="create-title"
        />

        {!menuIsOpen && (
          <input
            data-testid="title-tag-input"
            className="create-title__text-input"
            type="text"
            value={text}
            onChange={(e) => setText(e.target.value)}
            name="title-tag"
            aria-label="Title"
          />
        )}
        {menuIsOpen && (
          <div className="create-title__menu-footer">
            <input
              type="text"
              placeholder="Enter your brand (optional)"
              onChange={(e) => setBrand(e.target.value)}
              value={brand}
              className="create-title__brand"
              aria-label="Enter your brand (optional)"
            />
            <button
              data-testid="reload-titles"
              className="create-title__reload"
              disabled={isLoading}
              onClick={() => mutate(undefined, { revalidate: true })}
            >
              <RotateCw />
            </button>
            <Button
              disabled={isLoading}
              variant="surface"
              size="1"
              onClick={() => setMenuIsOpen(false)}
            >
              Close
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
