import { useEffect, useState } from 'react';
import { Loader, BookOpen, CheckCircle2, ArrowRight, Sparkles } from 'lucide-react';
import Card from '../ui/Card';
import Button from '../ui/Button';
import Tag from '../ui/Tag';
import { getOrGenerateThemeSession } from '../../lib/themeSessionService';

/**
 * Normalize the content payload coming back from PocketBase, which may be
 * either an object or a JSON string depending on how it was written.
 */
function normalizeContent(raw) {
  if (!raw) return null;
  if (typeof raw === 'string') {
    try { return JSON.parse(raw); } catch { return null; }
  }
  return raw;
}

export default function ThemeSessionView({
  curriculumVersionId,
  weekContent,
  alreadyCompleted = false,
  onCompleted,
  onPracticeTopic,
}) {
  const [record, setRecord] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [marked, setMarked] = useState(alreadyCompleted);

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setError(null);
    getOrGenerateThemeSession(curriculumVersionId, weekContent)
      .then((rec) => { if (!cancelled) setRecord(rec); })
      .catch((err) => { if (!cancelled) setError(err.message || 'Failed to load theme session.'); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [curriculumVersionId, weekContent?.weekNumber]);

  if (loading) {
    return (
      <Card className="w-full text-center py-16">
        <Loader size={48} className="mx-auto text-teal animate-spin mb-4" />
        <p className="font-medium text-lg">Preparing this week's theme session…</p>
        <p className="text-fg-muted text-sm mt-2">This may take 30–90 seconds the first time — the result is cached.</p>
      </Card>
    );
  }

  if (error) {
    return (
      <Card className="w-full border border-red-200 bg-red-50 text-red-900 p-6">
        <p className="font-bold mb-1">Could not load the theme session</p>
        <p className="text-sm">{error}</p>
      </Card>
    );
  }

  const content = normalizeContent(record?.content);
  if (!content) {
    return (
      <Card className="w-full p-6">
        <p className="text-fg-muted italic">No theme session content available yet.</p>
      </Card>
    );
  }

  const handleFinish = () => {
    if (marked) return;
    setMarked(true);
    if (typeof onCompleted === 'function') {
      onCompleted(record);
    }
  };

  return (
    <div className="space-y-6">
      <Card className="w-full p-6">
        <div className="flex items-center gap-2 mb-3">
          <Sparkles size={18} className="text-teal" />
          <Tag variant="dark" className="text-[10px] uppercase tracking-wide">Theme Session</Tag>
          <Tag variant="accent" className="text-[10px]">{weekContent.theme}</Tag>
          {marked && <Tag variant="success" className="text-[10px]">Completed</Tag>}
        </div>
        <h2 className="text-2xl md:text-3xl font-bold text-teal mb-2">{content.title}</h2>
        <p className="text-fg-muted">{content.intro}</p>
      </Card>

      {content.topicSections.map((section, idx) => (
        <Card key={section.topic_id || idx} className="w-full p-6">
          <div className="flex items-center gap-2 mb-3">
            <BookOpen size={18} className="text-teal" />
            <Tag variant="dark" className="text-[10px]">Topic {idx + 1} of {content.topicSections.length}</Tag>
          </div>
          <h3 className="text-xl font-bold mb-3">{section.label}</h3>
          <div
            className="prose dark:prose-invert max-w-none"
            dangerouslySetInnerHTML={{ __html: section.summary }}
          />
          {typeof onPracticeTopic === 'function' && (
            <div className="mt-4 pt-4 border-t border-bg-warm">
              <button
                type="button"
                onClick={() => onPracticeTopic(section.topic_id)}
                className="inline-flex items-center text-teal font-medium text-sm hover:underline"
              >
                Practice this topic <ArrowRight size={14} className="ml-1" />
              </button>
            </div>
          )}
        </Card>
      ))}

      <Card className="w-full p-6">
        <h3 className="text-lg font-bold mb-3">How these connect</h3>
        <div
          className="prose dark:prose-invert max-w-none"
          dangerouslySetInnerHTML={{ __html: content.connections }}
        />
      </Card>

      <Card className="w-full p-6">
        <h3 className="text-lg font-bold mb-3">Key takeaways</h3>
        <ul className="list-disc pl-5 space-y-1 text-sm">
          {content.keyTakeaways.map((t, i) => (
            <li key={i}>{t}</li>
          ))}
        </ul>
      </Card>

      <div className="flex justify-end">
        <Button onClick={handleFinish} disabled={marked}>
          {marked ? (
            <span className="flex items-center"><CheckCircle2 size={16} className="mr-2" /> Session completed</span>
          ) : (
            'Mark session as completed'
          )}
        </Button>
      </div>
    </div>
  );
}
