import React, { useRef, useState } from 'react';
import DraftManager, { type DraftManagerRef } from '../utilities/DraftManager.js';
import ErrorMessage from '../components/ErrorMessage.js';
import { useCompetitorUrls, useDraft, useInsights, useKeywords } from '../Context.js';
import Loading from '../components/Loading.js';
import InfoBar from '../components/InfoBar.js';
import { RotateCw } from 'lucide-react';
import GuidanceItem from '../components/GuidanceItem.js';
import GuidanceItemSelect from '../components/GuidanceItemSelect.js';
import GuidanceItemTextArea from '../components/GuidanceItemTextArea.js';
import GuidanceItemBadge from '../components/GuidanceItemBadge.js';
import './Guidance.css';

const Guidance = ({}: { setTab?: (index: number) => void; nextTab?: number }) => {
  const draft = useDraft();
  const keywords = useKeywords();
  const competitorUrls = useCompetitorUrls();
  const insights = useInsights();
  const [draftLoading, setDraftLoading] = useState(true);
  const [error, setError] = useState(false);
  const DraftManagerRef = useRef<DraftManagerRef>(null);
  const dateInsightsGenerated = insights?.generatedTime
    ? new Date(insights.generatedTime).toLocaleString('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      })
    : null;

  const arraysEqual = (a: string[], b: string[]) =>
    a.length === b.length && a.every((v) => new Set(b).has(v));
  if (dateInsightsGenerated && !arraysEqual(insights.keywords || [], keywords)) {
    DraftManagerRef?.current?.regenerateInsights();
  }

  if (!keywords.length || competitorUrls.length < 10) {
    return (
      <div>
        <InfoBar>
          Keywords and at least 10 competitor URLs are required, please go back to the previous
          screens to select some.
        </InfoBar>
      </div>
    );
  }

  return (
    <div
      className={`guidance ${draftLoading ? 'guidance--loading' : ''} ${error ? 'guidance--error' : ''}`}
    >
      <DraftManager
        ref={DraftManagerRef}
        isLoading={(loading) => setDraftLoading(loading)}
        hasError={(error) => setError(error)}
      />
      {(error || (!draftLoading && !draft.lastUpdated)) && (
        <ErrorMessage>
          There&apos;s been an error communicating with our systems. Changes to your guidance are
          currently unsaved. You can leave this window open whilst we try to re-establish a
          connection, or restart the application.
        </ErrorMessage>
      )}
      {draftLoading && <Loading />}
      {!draftLoading && draft.id && (
        <>
          <div className="guidance__description">
            <p>
              Content guidance comes from top competitors’ pages ranking for your keywords. Remove
              irrelevant ones for better results.
            </p>
            <p className="guidance__refresh">
              <RotateCw onClick={() => DraftManagerRef?.current?.regenerateInsights()} />
              {dateInsightsGenerated
                ? `Guidance generated ${dateInsightsGenerated}`
                : 'Generating guidance…'}
            </p>
          </div>
          <div className="guidance__items">
            <details open>
              <summary>
                <span>
                  Objective
                  <GuidanceItemBadge insight={insights?.data?.objective} />
                </span>
              </summary>
              <GuidanceItem description="Content that performs well for this topic focuses on the following objective.">
                <GuidanceItemTextArea
                  draftId={draft.id}
                  insight={insights?.data?.objective}
                  refreshInsights={() => DraftManagerRef?.current?.refreshInsights()}
                  label="Objective"
                />
              </GuidanceItem>
            </details>

            <details open>
              <summary>
                <span>
                  Audience
                  <GuidanceItemBadge insight={insights?.data?.audience} />
                </span>
              </summary>
              <GuidanceItem description="Content that performs well for this topic targets the following audiences.">
                <GuidanceItemTextArea
                  draftId={draft.id}
                  insight={insights?.data?.audience}
                  refreshInsights={() => DraftManagerRef?.current?.refreshInsights()}
                  label="Audience"
                />
              </GuidanceItem>
            </details>

            <details open>
              <summary>
                <span>
                  Journey stage
                  <GuidanceItemBadge insight={insights?.data?.journeyStage} />
                </span>
              </summary>
              <GuidanceItem
                description="Matching your content to the customer journey stage of highly ranking pages might
                help your page to rank higher."
              >
                <GuidanceItemSelect
                  draftId={draft.id}
                  insight={insights?.data?.journeyStage}
                  refreshInsights={() => DraftManagerRef?.current?.refreshInsights()}
                  label="Journey stage"
                />
              </GuidanceItem>
            </details>

            <details open>
              <summary>
                <span>
                  Content type
                  <GuidanceItemBadge insight={insights?.data?.contentType} />
                </span>
              </summary>
              <GuidanceItem description="Matching your content to the formats of highly ranking pages might help your page to rank higher.">
                <GuidanceItemSelect
                  draftId={draft.id}
                  insight={insights?.data?.contentType}
                  refreshInsights={() => DraftManagerRef?.current?.refreshInsights()}
                  label="Content type"
                />
              </GuidanceItem>
            </details>

            {/*
            <details open>
              <summary>Questions to answer</summary>
              <div className="guidance__item-description">
                Answer the questions your audience is asking about this topic to make your content
                more valuable to them and improve your rank.
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>Body copy suggestions</summary>
              <div className="guidance__item-description">
                These are the most important terms mentioned on top ranking pages. You'll want to
                discuss these terms in similar detail.
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>Length</summary>
              <div className="guidance__item-description">
                People are looking for medium length content — top pages have an average of 1,647
                words.
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>Readability</summary>
              <div className="guidance__item-description">
                Aim for a 8th & 9th grade reading level for this topic audience
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>Title tag patterns</summary>
              <div className="guidance__item-description">
                Based on AI analysis, these topics are common in title tags on top ranking pages.
                Consider using at least one in your title tag:
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>H1 patterns</summary>
              <div className="guidance__item-description">
                Based on AI analysis, these topics are common in H1s on top ranking pages. Consider
                using at least one in your H1:
              </div>
              <div className="guidance__item-description">
                Based on AI analysis, these topics are common in H1s on top ranking pages. Consider
                using at least one in your H1:
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>H2 patterns</summary>
              <div className="guidance__item-description">
                Based on AI analysis, these topics are common in H2s on top ranking pages. Consider
                using at least one in your H2:
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            <details open>
              <summary>H3 patterns</summary>
              <div className="guidance__item-description">
                Based on AI analysis, these topics are common in H3s on top ranking pages. Consider
                using at least one in your H3:
              </div>
              <div className="guidance__item-configuration">Hello, world!</div>
            </details>
            */}
          </div>
        </>
      )}
    </div>
  );
};

export default Guidance;
