'use client';

import React, { use, useEffect, useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { getApiPath } from '@/lib/basePath';
import { resolveAssetPath } from '@/lib/assetUrl';
import {
  ArrowLeft,
  ChevronRight,
  Loader2,
  AlertTriangle,
  Check,
} from 'lucide-react';

const COLUMN_CONFIG = [
  { id: 'task1_general', label: 'Task 1', sub: 'General Training', color: '#4A1429', minWords: 150, time: 20 },
  { id: 'task1_academic', label: 'Task 1', sub: 'Academic', color: '#6B1E3D', minWords: 150, time: 20 },
  { id: 'task2', label: 'Task 2', sub: 'Common', color: '#3D0F22', minWords: 250, time: 40 },
];

function isEmojiLike(value) {
  if (!value || typeof value !== 'string') return false;
  return /\p{Extended_Pictographic}/u.test(value);
}

async function parseJsonResponse(res) {
  const text = await res.text();
  if (!text) return {};
  try {
    return JSON.parse(text);
  } catch {
    throw new Error('Unexpected response from the server.');
  }
}

const STEPS = ['Choose question', 'Task type', 'Write Essay', 'Review feedback'];

function StepBar({ step = 2 }) {
  return (
    <div className="flex items-center justify-center gap-2 sm:gap-3 py-4 px-4 flex-wrap">
      {STEPS.map((label, index) => {
        const number = index + 1;
        const isActive = number === step;
        const isDone = number < step;
        return (
          <React.Fragment key={label}>
            <div className={`flex items-center gap-2 text-sm font-bold transition-colors ${number <= step ? 'text-[#4A1429]' : 'text-gray-300'}`}>
              <span
                className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-black shrink-0 ${isDone ? 'bg-[#D4B038] text-white' : isActive ? 'bg-[#4A1429] text-white' : 'bg-gray-200 text-gray-400'}`}
              >
                {isDone ? <Check className="w-4 h-4" /> : number}
              </span>
              <span className="hidden sm:inline">{label}</span>
            </div>
            {index < STEPS.length - 1 && (
              <ChevronRight className={`w-4 h-4 shrink-0 ${isDone ? 'text-[#D4B038]' : 'text-gray-300'}`} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

export default function WritingAnalyserTaskPage({ params }) {
  const navigate = useNavigate();
  const resolvedParams = params ? use(params) : {};
  const slug = resolvedParams?.slug ? decodeURIComponent(resolvedParams.slug) : '';
  const [topic, setTopic] = useState(null);
  const [tasks, setTasks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let active = true;
    const loadTasks = async () => {
      try {
        setLoading(true);
        setError('');
        const res = await fetch(getApiPath(`/api/writing-analyser/tasks?topic=${encodeURIComponent(slug)}`));
        const data = await parseJsonResponse(res);
        if (!res.ok) throw new Error(data?.message || 'Failed to load tasks.');
        if (active) {
          setTopic(data?.topic || null);
          setTasks(Array.isArray(data?.tasks) ? data.tasks : []);
        }
      } catch (err) {
        if (active) setError(err?.message || 'Unable to load tasks.');
      } finally {
        if (active) setLoading(false);
      }
    };
    if (slug) loadTasks();
    return () => {
      active = false;
    };
  }, [slug]);

  const groupedTasks = useMemo(() => {
    const groups = { task1_general: [], task1_academic: [], task2: [] };
    tasks.forEach((task) => {
      const number = (task.taskNumber || '').toLowerCase();
      const type = (task.taskType || '').toLowerCase();
      const isTask1 = number.includes('task 1');

      if (isTask1) {
        if (type.includes('general')) {
          groups.task1_general.push(task);
        } else if (type.includes('academic')) {
          groups.task1_academic.push(task);
        } else {
          groups.task1_general.push(task);
        }
      } else {
        groups.task2.push(task);
      }
    });
    return groups;
  }, [tasks]);

  const topicLabel = topic?.name || slug;
  const topicIcon = topic?.icon || '';
  const topicHasEmoji = isEmojiLike(topicIcon);
  const topicIconPath = topicHasEmoji ? '' : resolveAssetPath(topicIcon);

  return (
    <div className="min-h-screen" style={{ background: '#FAF5F0' }}>
<div className="max-w-4xl mx-auto px-4 pt-5">
        <div className="rounded-2xl" style={{ background: 'white', border: '1px solid #E5DDD5' }}>
          <StepBar step={2} />
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-4 py-6">
        <div className="text-center mb-6">
          <div
            className="inline-flex items-center gap-2 rounded-full border px-4 py-2 mb-3"
            style={{ background: 'rgba(212,176,56,0.08)', borderColor: 'rgba(212,176,56,0.3)' }}
          >
            {topicHasEmoji && <span className="text-base">{topicIcon}</span>}
            {!topicHasEmoji && topicIconPath && (
              <img src={topicIconPath} alt={topicLabel} className="w-4 h-4 object-contain" />
            )}
            <span className="text-sm font-black" style={{ color: '#8B6914' }}>Topic: {topicLabel}</span>
          </div>
          <h2 className="text-3xl font-black mb-2" style={{ color: '#4A1429' }}>Choose Your Task</h2>
          <p className="text-base" style={{ color: '#8B6B7A' }}>Select a question and start practising, or view the glossary first</p>
        </div>

        {loading && (
          <div className="flex items-center justify-center gap-2 text-sm font-semibold" style={{ color: '#6B4455' }}>
            <Loader2 className="w-4 h-4 animate-spin" />
            Loading tasks...
          </div>
        )}

        {!loading && error && (
          <div className="flex items-center justify-center gap-2 text-sm font-semibold" style={{ color: '#B91C1C' }}>
            <AlertTriangle className="w-4 h-4" />
            {error}
          </div>
        )}

        {!loading && !error && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
            {COLUMN_CONFIG.map((col) => {
              const list = groupedTasks[col.id] || [];
              return (
                <div
                  key={col.id}
                  className="rounded-2xl overflow-hidden shadow-sm"
                  style={{ background: 'white', border: '1px solid #E5DDD5' }}
                >
                  <div className="px-5 py-4 text-center" style={{ background: col.color }}>
                    <div className="text-2xl font-black text-white">{col.label}</div>
                    <div className="text-sm font-bold mt-0.5" style={{ color: 'rgba(212,176,56,0.9)' }}>{col.sub}</div>
                    <div className="flex justify-center gap-3 mt-2">
                      <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(255,255,255,0.12)', color: 'rgba(255,255,255,0.8)' }}>
                        Time: {col.time} min
                      </span>
                      <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{ background: 'rgba(255,255,255,0.12)', color: 'rgba(255,255,255,0.8)' }}>
                        Words: {col.minWords}+
                      </span>
                    </div>
                  </div>

                  <div className="p-3 space-y-2 max-h-[420px] overflow-y-auto">
                    {list.length === 0 && (
                      <div className="p-3 rounded-xl text-xs font-semibold text-center" style={{ color: '#8B6B7A', background: '#FAF5F0', border: '1px solid #F0E8E0' }}>
                        No tasks available.
                      </div>
                    )}
                    {list.map((task, index) => {
                      const title = `${topicLabel.toUpperCase()} - ${(task.taskName || task.taskSlug || 'TASK').toUpperCase()}`;
                      return (
                        <div key={task.id} className="p-3 rounded-xl" style={{ background: '#FAF5F0', border: '1px solid #F0E8E0' }}>
                          <p className="text-xs font-black uppercase tracking-wide mb-2" style={{ color: '#4A1429' }}>
                            {index + 1}. {title}
                          </p>
                          <div className="flex gap-2">
                            <motion.button
                              onClick={() => navigate(`/account/writing-analyser/write-essay/${encodeURIComponent(slug)}?task=${task.id}`)}
                              whileHover={{ scale: 1.04 }}
                              whileTap={{ scale: 0.97 }}
                              className="flex-1 py-1.5 rounded-lg text-xs font-extrabold"
                              style={{ background: col.color, color: 'white' }}
                            >
                              Start
                            </motion.button>
                            <motion.button
                              onClick={() => navigate(`/account/writing-analyser/glossary/${encodeURIComponent(slug)}?task=${task.id}`)}
                              whileHover={{ scale: 1.04 }}
                              whileTap={{ scale: 0.97 }}
                              className="flex-1 py-1.5 rounded-lg text-xs font-extrabold"
                              style={{ background: 'white', color: col.color, border: `1.5px solid ${col.color}` }}
                            >
                              Glossary
                            </motion.button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        <div className="mt-6 text-center">
          <button onClick={() => navigate('/account/writing-analyser')} className="text-sm font-semibold flex items-center gap-1.5 mx-auto" style={{ color: '#8B6B7A' }}>
            <ArrowLeft className="w-4 h-4" /> Back to topics
          </button>
        </div>

      </div>
    </div>
  );
}
