import React, { useEffect, useMemo, useState } from 'react';
import { Info } from 'lucide-react';
import { DigestConcept, DigestSection } from '../../types';

interface DigestProps {
  sections: DigestSection[];
}

function slugify(value: string) {
  return value
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '');
}

function escapeRegExp(value: string) {
  return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function splitIntoSentences(text: string) {
  return text
    .split(/(?<=[.!?])\s+/)
    .map((sentence) => sentence.trim())
    .filter(Boolean);
}

function cleanListMarkerFragments(text: string) {
  return text
    .replace(/\s+\d+\.\s*$/, '')
    .replace(/^\d+\.\s*/, '')
    .trim();
}

function buildSectionSlices(text: string) {
  const sentences = splitIntoSentences(text)
    .map(cleanListMarkerFragments)
    .filter(Boolean);

  if (sentences.length <= 2) {
    return {
      intro: text,
      bullets: [] as string[],
    };
  }

  return {
    intro: cleanListMarkerFragments(sentences.slice(0, 2).join(' ')),
    bullets: sentences.slice(2),
  };
}

function collectConcepts(sections: DigestSection[]): DigestConcept[] {
  const seen = new Map<string, DigestConcept>();

  for (const section of sections) {
    const explicitConcepts = section.concepts ?? [];
    for (const concept of explicitConcepts) {
      const key = concept.term.trim().toLowerCase();
      if (!key || seen.has(key)) continue;
      seen.set(key, concept);
    }

    if (section.keyConcept) {
      const key = section.keyConcept.trim().toLowerCase();
      if (!key || seen.has(key)) continue;
      seen.set(key, {
        term: section.keyConcept.trim(),
        definition: section.content,
      });
    }
  }

  return [...seen.values()];
}

function HighlightedText({
  text,
  concepts,
  onConceptClick,
  as = 'p',
  className = 'text-[15px] leading-8 text-zinc-300',
}: {
  text: string;
  concepts: DigestConcept[];
  onConceptClick: (concept: DigestConcept) => void;
  as?: 'p' | 'span';
  className?: string;
}) {
  const Wrapper = as;

  if (concepts.length === 0) {
    return <Wrapper className={className}>{text}</Wrapper>;
  }

  const terms = concepts.map((concept) => concept.term).sort((a, b) => b.length - a.length);
  const regex = new RegExp(`\\b(${terms.map(escapeRegExp).join('|')})\\b`, 'gi');
  const parts = text.split(regex);

  return (
    <Wrapper className={className}>
      {parts.map((part, index) => {
        const concept = concepts.find((item) => item.term.toLowerCase() === part.toLowerCase());

        if (!concept) {
          return <span key={`${part}-${index}`}>{part}</span>;
        }

        return (
          <button
            key={`${concept.term}-${index}`}
            id={`studyflow-concept-trigger-${slugify(concept.term)}`}
            type="button"
            onClick={() => onConceptClick(concept)}
            className="mx-0.5 rounded bg-teal-500/12 px-1.5 py-0.5 font-medium text-teal-300 underline decoration-teal-500/30 underline-offset-4 transition-colors hover:bg-teal-500/18 focus:outline-none focus:ring-2 focus:ring-teal-500/50"
          >
            {part}
          </button>
        );
      })}
    </Wrapper>
  );
}

export function Digest({ sections }: DigestProps) {
  const concepts = useMemo(() => collectConcepts(sections), [sections]);
  const [activeConcept, setActiveConcept] = useState<DigestConcept | null>(concepts[0] ?? null);

  useEffect(() => {
    setActiveConcept(concepts[0] ?? null);
  }, [concepts]);

  return (
    <div id="studyflow-digest-mode" className="flex h-full w-full overflow-hidden">
      <div id="studyflow-digest-reader" className="flex-1 overflow-y-auto px-8 py-10">
        <div className="mx-auto flex w-full max-w-[1680px] gap-12">
          <div className="min-w-0 flex-1">
            <header id="studyflow-digest-header" className="mb-10 border-b border-white/5 pb-6">
              <h2 className="mb-2 text-[2rem] font-semibold tracking-tight text-zinc-100">Study Digest</h2>
              <p className="text-base text-zinc-400">
                Read through the synthesized concepts below. Click the highlighted terms to bring them into focus.
              </p>
            </header>

            <div className="space-y-12">
              {sections.map((section, index) => {
                const sectionConcepts = concepts.filter((concept) =>
                  (section.concepts ?? []).some((item) => item.term.toLowerCase() === concept.term.toLowerCase()) ||
                  (section.keyConcept ? section.keyConcept.toLowerCase() === concept.term.toLowerCase() : false),
                );
                const sectionSlices = buildSectionSlices(section.content);

                return (
                  <section
                    key={`${section.title}-${index}`}
                    id={`studyflow-digest-section-${index + 1}`}
                    className="relative grid grid-cols-[64px_minmax(0,1fr)] gap-5"
                  >
                    <div className="flex flex-col items-center pt-0.5">
                      <div className="flex h-11 w-11 items-center justify-center rounded-2xl border border-teal-500/15 bg-teal-500/[0.06] text-sm font-semibold text-teal-300">
                        {String(index + 1).padStart(2, '0')}
                      </div>
                      {index < sections.length - 1 && <div className="mt-3 h-full w-px bg-gradient-to-b from-teal-500/25 to-transparent" />}
                    </div>

                    <div className="min-w-0 pb-4">
                      <div className="mb-5">
                        <h3 className="text-[1.45rem] font-semibold leading-tight tracking-tight text-zinc-50">
                          {section.keyConcept || section.title}
                        </h3>
                      </div>

                      <div className="space-y-5">
                        <HighlightedText
                          text={sectionSlices.intro}
                          concepts={sectionConcepts}
                          onConceptClick={setActiveConcept}
                        />

                        {sectionSlices.bullets.length > 0 && (
                          <ul className="space-y-3 pl-0">
                            {sectionSlices.bullets.map((sentence, sentenceIndex) => (
                              <li
                                key={`${section.title}-bullet-${sentenceIndex}`}
                                className="flex items-start gap-4 text-[15px] leading-7 text-zinc-300"
                              >
                                <span className="mt-2 h-2.5 w-2.5 flex-shrink-0 rounded-full bg-amber-400/80" />
                                <span className="min-w-0">
                                  <HighlightedText
                                    text={sentence}
                                    concepts={sectionConcepts}
                                    onConceptClick={setActiveConcept}
                                    as="span"
                                    className="text-[15px] leading-7 text-zinc-300"
                                  />
                                </span>
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    </div>
                  </section>
                );
              })}
            </div>
          </div>

          <aside
            id="studyflow-concept-spotlight"
            className="studyflow-concept-spotlight sticky top-0 h-fit w-80 flex-shrink-0 border-l border-white/5 pl-8 pt-1"
          >
            <h4 className="mb-6 text-xs font-semibold uppercase tracking-[0.24em] text-zinc-500">Concept Spotlight</h4>

            {activeConcept ? (
              <div
                id={`studyflow-concept-panel-${slugify(activeConcept.term)}`}
                className="rounded-2xl border border-white/5 bg-white/[0.02] p-5"
              >
                <p className="text-2xl font-medium tracking-tight text-teal-300">{activeConcept.term}</p>
                <div className="my-4 h-1 w-10 rounded-full bg-teal-500/30" />
                <p className="text-[15px] leading-7 text-zinc-300">{activeConcept.definition}</p>
              </div>
            ) : (
              <div className="rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-6 text-zinc-500">
                <Info size={20} className="mb-4 text-zinc-600" />
                <p className="text-sm leading-relaxed">
                  Select a highlighted concept in the digest to see its definition here.
                </p>
              </div>
            )}
          </aside>
        </div>
      </div>
    </div>
  );
}
