'use client';

import { useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import {
  AlertTriangle,
  ArrowRight,
  BadgeAlert,
  BookOpen,
  BriefcaseBusiness,
  BusFront,
  CircleDollarSign,
  Clapperboard,
  Cpu,
  Dumbbell,
  FlaskConical,
  HeartPulse,
  Landmark,
  Layers3,
  Leaf,
  Loader2,
  MessagesSquare,
  Newspaper,
  Palette,
  PawPrint,
  Plane,
  Rocket,
  Search,
  ShieldAlert,
  Tractor,
  Utensils,
  UsersRound,
} from 'lucide-react';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { getApiPath } from '@/lib/basePath';

const TOPIC_ICONS = {
  animals: PawPrint,
  art: Palette,
  entertainment: Clapperboard,
  environment: Leaf,
  fake_news: BadgeAlert,
  crime: ShieldAlert,
  communication: MessagesSquare,
  family: UsersRound,
  farm: Tractor,
  food: Utensils,
  healthcare: HeartPulse,
  money: CircleDollarSign,
  news: Newspaper,
  society: Landmark,
  space: Rocket,
  sport: Dumbbell,
  technology: Cpu,
  transport: BusFront,
  travel: Plane,
  'wealth-gap': Layers3,
  work: BriefcaseBusiness,
  science: FlaskConical,
};

async function parseJsonResponse(response) {
  const text = await response.text();
  if (!text) return {};

  try {
    return JSON.parse(text);
  } catch {
    throw new Error('Unexpected response from the server.');
  }
}

export default function WritingAnalyserTopicExplorer() {
  const navigate = useNavigate();
  const [topics, setTopics] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [query, setQuery] = useState('');

  useEffect(() => {
    let active = true;

    async function loadTopics() {
      try {
        setLoading(true);
        setError('');
        const response = await fetch(getApiPath('/api/writing-analyser/topics'));
        const data = await parseJsonResponse(response);
        if (!response.ok) throw new Error(data?.message || 'Failed to load topics.');
        if (active) setTopics(Array.isArray(data?.topics) ? data.topics : []);
      } catch (loadError) {
        if (active) setError(loadError?.message || 'Unable to load topics.');
      } finally {
        if (active) setLoading(false);
      }
    }

    loadTopics();
    return () => {
      active = false;
    };
  }, []);

  const filteredTopics = useMemo(() => {
    const normalizedQuery = query.trim().toLowerCase();
    if (!normalizedQuery) return topics;
    return topics.filter((topic) => String(topic?.name || '').toLowerCase().includes(normalizedQuery));
  }, [query, topics]);

  return (
    <div>
      <div className="mx-auto max-w-[1480px] px-5 py-20 sm:px-8 lg:px-10 lg:py-24">
        <div className="rounded-[2rem] border border-[#DED0C8] bg-white p-5 shadow-[0_22px_60px_rgba(74,20,41,0.09)] sm:p-8 lg:p-10">
          <div className="flex flex-col justify-between gap-6 border-b border-[#ECE2DD] pb-7 lg:flex-row lg:items-end">
            <div className="max-w-3xl">
              <p className="text-xs font-extrabold uppercase tracking-[0.2em] text-[#9A7417]">Start your practice</p>
              <h2 className="mt-3 text-3xl font-black tracking-[-0.025em] text-[#4A1429] sm:text-4xl">Choose an IELTS writing topic</h2>
              <p className="mt-3 text-sm leading-6 text-[#735763] sm:text-base">Choose a subject, select a question and write your response directly in the analyser.</p>
            </div>
            <label className="relative block w-full lg:w-80">
              <span className="sr-only">Search practice topics</span>
              <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-[#9A7E89]" aria-hidden="true" />
              <input
                type="search"
                value={query}
                onChange={(event) => setQuery(event.target.value)}
                placeholder="Search topics"
                className="min-h-12 w-full rounded-xl border border-[#DED1CA] bg-[#FCF9F7] py-2 pl-10 pr-4 text-sm text-[#4A1429] outline-none transition focus:border-[#B9922C] focus:ring-2 focus:ring-[#D4B038]/20"
              />
            </label>
          </div>

          {loading && (
            <div className="flex min-h-64 items-center justify-center gap-2 text-sm font-semibold text-[#6B4455]" role="status">
              <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" /> Loading writing topics…
            </div>
          )}

          {!loading && error && (
            <div className="flex min-h-64 flex-col items-center justify-center gap-3 text-center" role="alert">
              <AlertTriangle className="h-6 w-6 text-[#A13C35]" aria-hidden="true" />
              <p className="text-sm font-semibold text-[#6B4455]">{error}</p>
            </div>
          )}

          {!loading && !error && topics.length === 0 && (
            <div className="flex min-h-64 items-center justify-center text-center text-sm font-semibold text-[#6B4455]">No topics are available right now.</div>
          )}

          {!loading && !error && topics.length > 0 && filteredTopics.length === 0 && (
            <div className="flex min-h-64 items-center justify-center text-center text-sm font-semibold text-[#6B4455]">No topics match “{query}”.</div>
          )}

          {!loading && !error && filteredTopics.length > 0 && (
            <div className="mt-7 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5" aria-live="polite">
              {filteredTopics.map((topic) => {
                const TopicIcon = TOPIC_ICONS[topic.slug] || BookOpen;

                return (
                  <motion.button
                    key={topic.id}
                    type="button"
                  onClick={() => navigate(`/tools-dashboard/writing-analyser/task/${topic.slug}`)}
                    whileHover={{ y: -4 }}
                    whileTap={{ scale: 0.98 }}
                    className="group flex min-h-40 flex-col items-start justify-between rounded-2xl border border-[#E6DAD3] bg-[#FCF9F7] p-5 text-left shadow-[0_6px_20px_rgba(74,20,41,0.03)] transition-colors hover:border-[#C79F36] hover:bg-white hover:shadow-[0_12px_30px_rgba(74,20,41,0.08)]"
                    aria-label={`Choose ${topic.name} writing topic`}
                  >
                    <span className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[#4A1429] text-[#E2BE4A] shadow-[0_8px_18px_rgba(74,20,41,0.16)] transition-transform group-hover:scale-105">
                      <TopicIcon className="h-6 w-6" strokeWidth={1.8} aria-hidden="true" />
                    </span>
                    <span className="flex w-full items-end justify-between gap-3">
                      <span className="text-sm font-extrabold leading-5 text-[#4A1429]">{topic.name}</span>
                      <ArrowRight className="h-4 w-4 shrink-0 text-[#B58B24] transition-transform group-hover:translate-x-1" aria-hidden="true" />
                    </span>
                  </motion.button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
