'use client';

import React, { Suspense, use, useEffect, useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { useAuth } from '@/lib/AuthContext';
import { useSearchParams } from 'next/navigation';
import { resolveAssetPath } from '@/lib/assetUrl';
import { getApiPath } from '@/lib/basePath';
import {
  ArrowLeft,
  BookOpen,
  ChevronRight,
  Loader2,
  AlertTriangle,
  Check,
  PenLine,
} from 'lucide-react';

const STEPS = ['Choose question', 'Task type', 'Write Essay', 'Review feedback'];

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.');
  }
}


function getStep3Label(task) {
  const number = (task?.taskNumber || '').toLowerCase();
  const type = (task?.taskType || '').toLowerCase();
  if (number.includes('task 1')) {
    return type.includes('academic') ? 'Write Report' : 'Write Letter';
  }
  return 'Write Essay';
}

function StepBar({ step, task }) {
  const step3Label = getStep3Label(task);
  const steps = ['Choose question', 'Task type', step3Label, 'Review feedback'];
  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>
  );
}

function WritingAnalyserWriteEssayContent({ params }) {
  const navigate = useNavigate();
  const { user } = useAuth();
  const searchParams = useSearchParams();
  const resolvedParams = params ? use(params) : {};
  const slug = resolvedParams?.slug ? decodeURIComponent(resolvedParams.slug) : '';
  const initialTaskId = searchParams.get('task');

  const [topic, setTopic] = useState(null);
  const [tasks, setTasks] = useState([]);
  const [activeTaskId, setActiveTaskId] = useState(initialTaskId);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const [essay, setEssay] = useState('');
  const [hasStarted, setHasStarted] = useState(false);
  const [isRunning, setIsRunning] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [seconds, setSeconds] = useState(0);

  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) return;
        setTopic(data?.topic || null);
        const list = Array.isArray(data?.tasks) ? data.tasks : [];
        setTasks(list);

        if (!activeTaskId) {
          setActiveTaskId(list[0]?.id?.toString() || '');
        }
      } catch (err) {
        if (active) setError(err?.message || 'Unable to load tasks.');
      } finally {
        if (active) setLoading(false);
      }
    };

    if (slug) loadTasks();
    return () => {
      active = false;
    };
  }, [slug]);

  const activeTask = useMemo(() => {
    if (!activeTaskId) return tasks[0] || null;
    return tasks.find((task) => task.id?.toString() === activeTaskId) || tasks[0] || null;
  }, [tasks, activeTaskId]);

  const topicLabel = topic?.name || slug;
  const taskNumber = (activeTask?.taskNumber || '').toLowerCase();
  const isTask1 = taskNumber.includes('task 1');
  const minWords = isTask1 ? 150 : 250;
  const timeMinutes = isTask1 ? 20 : 40;

  useEffect(() => {
    setSeconds(timeMinutes * 60);
    setHasStarted(false);
    setIsRunning(false);
    setIsSubmitting(false);
    setSubmitError('');
    setEssay('');
  }, [timeMinutes, activeTaskId]);

  useEffect(() => {
    if (!isRunning) return () => {};
    const timer = setInterval(() => {
      setSeconds((prev) => Math.max(0, prev - 1));
    }, 1000);
    return () => clearInterval(timer);
  }, [isRunning]);

  useEffect(() => {
    if (isRunning && seconds === 0) {
      setIsRunning(false);
    }
  }, [seconds, isRunning]);

  const wordCount = essay.trim() ? essay.trim().split(/\s+/).length : 0;
  const meetsMin = wordCount >= minWords;
  const progress = Math.min(100, (wordCount / minWords) * 100);

  const fmtTimer = (totalSeconds) => {
    const minutes = Math.floor(totalSeconds / 60);
    const secs = String(totalSeconds % 60).padStart(2, '0');
    return `${minutes}:${secs}`;
  };

  const instruction = `You should spend about ${timeMinutes} minutes on this task. Write at least ${minWords} words.`;

  const handleSubmit = async () => {
    if (!essay.trim()) {
      setSubmitError('Please write your response before submitting.');
      return;
    }
    if (!meetsMin) {
      setSubmitError(`Please write at least ${minWords} words.`);
      return;
    }

    setSubmitError('');
    setIsSubmitting(true);
    setIsRunning(false);
    try {
      const res = await fetch(getApiPath('/api/writing-analyser/submit'), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          taskId: activeTask?.id,
          essay,
          userId: user?.id ?? null,
        }),
      });
      const payload = await parseJsonResponse(res);
      if (!res.ok) {
        const upstream = payload?.upstream_status ? ` (upstream ${payload.upstream_status})` : '';
        const detail = payload?.details
          ? ` ${String(payload.details).slice(0, 220)}`
          : '';
        throw new Error((payload?.message || 'Failed to submit essay.') + upstream + detail);
      }
      const redirectUrl = payload?.redirect_url;
      const taskKey = payload?.task_key;
      const target = redirectUrl || (taskKey ? `/tools/writing-analyser/result/${encodeURIComponent(taskKey)}` : '');
      if (target) {
        navigate(target);
        return;
      }
      throw new Error('Missing result key.');
    } catch (err) {
      setSubmitError(err?.message || 'Failed to submit essay.');
      setIsSubmitting(false);
    }
  };

  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={3} task={activeTask} />
        </div>
      </div>

      <div className="max-w-4xl mx-auto px-4 py-6">
        {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 task...
          </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 && activeTask && (
          <>
            <div className="mb-5 rounded-2xl overflow-hidden shadow-sm" style={{ border: '1px solid #E5DDD5' }}>
              <div className="px-5 py-3 flex items-center justify-between" style={{ background: '#4A1429' }}>
                <div>
                  <span className="text-xs font-black uppercase tracking-widest" style={{ color: 'rgba(212,176,56,0.8)' }}>
                    {(activeTask.taskNumber || 'Task').toUpperCase()} - {(activeTask.taskType || 'Common').toUpperCase()}
                  </span>
                  <div className="text-white font-black text-sm mt-0.5">
                    {topicLabel} - {activeTask.taskName}
                  </div>
                </div>
                <button
                  onClick={() => navigate(`/tools/writing-analyser/glossary/${encodeURIComponent(slug)}?task=${activeTask.id}`)}
                  className="flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-extrabold"
                  style={{ background: 'rgba(212,176,56,0.2)', color: '#D4B038', border: '1px solid rgba(212,176,56,0.4)' }}
                >
                  <BookOpen className="w-3.5 h-3.5" /> Glossary
                </button>
              </div>
              <div className="p-5 bg-white">
                <p className="text-base font-black mb-3" style={{ color: '#4A1429' }}>{instruction}</p>
                {activeTask.questionImage && (
                  <div className="rounded-xl overflow-hidden mb-4" style={{ border: '2px solid #D4B038' }}>
                    <div className="flex items-center justify-between px-4 py-2.5" style={{ background: '#4A1429' }}>
                      <span className="text-xs font-black uppercase tracking-widest" style={{ color: '#D4B038' }}>
                        Chart / Table / Diagram
                      </span>
                      <span className="text-[10px] font-semibold" style={{ color: 'rgba(255,255,255,0.5)' }}>
                        IELTS Academic Task 1
                      </span>
                    </div>
                    <img
                      src={resolveAssetPath(activeTask.questionImage)}
                      alt="Task chart"
                      className="block h-auto w-full object-contain"
                    />
                  </div>
                )}
                {(activeTask.questions || []).map((line, index) => (
                  line?.trim()
                    ? <p key={index} className="text-sm leading-relaxed mb-1.5" style={{ color: '#2D0F1C' }}>{line}</p>
                    : <div key={index} className="h-1.5" />
                ))}
              </div>
            </div>

            <div className="rounded-2xl overflow-hidden shadow-sm" style={{ border: '2px solid #E5DDD5' }}>
              <div className="flex items-center justify-between px-5 py-3" style={{ background: '#FAF5F0', borderBottom: '1px solid #E5DDD5' }}>
                <div className="flex items-center gap-3">
                  <span className="text-sm font-black" style={{ color: meetsMin ? '#16A34A' : '#4A1429' }}>
                    {wordCount} words {meetsMin ? 'OK' : `/ ${minWords} words`}
                  </span>
                  <div className="w-24 h-2 rounded-full overflow-hidden" style={{ background: '#E5DDD5' }}>
                    <motion.div
                      className="h-full rounded-full transition-all"
                      style={{ width: `${progress}%`, background: meetsMin ? '#16A34A' : '#D4B038' }}
                    />
                  </div>
                </div>
                {hasStarted && (
                  <span className="text-sm font-black tabular-nums" style={{ color: seconds < 300 ? '#DC2626' : '#4A1429' }}>
                    {fmtTimer(seconds)}
                  </span>
                )}
              </div>

              <textarea
                value={essay}
                onChange={(e) => setEssay(e.target.value)}
                placeholder={hasStarted ? 'Write your response here...' : 'Click start to begin the timed session...'}
                className="w-full resize-none p-5 text-base leading-relaxed focus:outline-none"
                style={{ background: 'white', color: '#2D0F1C', minHeight: 300, fontFamily: 'inherit' }}
                disabled={!hasStarted || isSubmitting}
              />

              <div className="flex items-center justify-between px-5 py-4" style={{ background: '#FAF5F0', borderTop: '1px solid #E5DDD5' }}>
                {!hasStarted ? (
                  <motion.button
                    onClick={() => {
                      setHasStarted(true);
                      setIsRunning(true);
                    }}
                    whileHover={{ scale: 1.04 }}
                    whileTap={{ scale: 0.97 }}
                    className="mx-auto px-8 py-3 rounded-xl font-extrabold text-base"
                    style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)', color: 'white', boxShadow: '0 4px 16px rgba(74,20,41,0.35)' }}
                  >
                    Start writing now
                  </motion.button>
                ) : isRunning ? (
                  <motion.button
                    onClick={handleSubmit}
                    whileHover={{ scale: 1.04 }}
                    whileTap={{ scale: 0.97 }}
                    disabled={!essay.trim() || !meetsMin || isSubmitting}
                    className="ml-auto px-8 py-3 rounded-xl font-extrabold text-base disabled:opacity-50"
                    style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22', boxShadow: '0 4px 16px rgba(212,176,56,0.4)' }}
                  >
                    Submit
                  </motion.button>
                ) : (
                  <div className="ml-auto flex items-center gap-3">
                    <motion.button
                      onClick={() => setIsRunning(true)}
                      whileHover={{ scale: 1.04 }}
                      whileTap={{ scale: 0.97 }}
                      className="px-6 py-3 rounded-xl font-extrabold text-base"
                      style={{ background: 'linear-gradient(135deg, #4A1429, #6B1E3D)', color: 'white', boxShadow: '0 4px 16px rgba(74,20,41,0.35)' }}
                    >
                      Resume
                    </motion.button>
                    <motion.button
                      onClick={handleSubmit}
                      whileHover={{ scale: 1.04 }}
                      whileTap={{ scale: 0.97 }}
                      disabled={!essay.trim() || !meetsMin || isSubmitting}
                      className="px-6 py-3 rounded-xl font-extrabold text-base disabled:opacity-50"
                      style={{ background: 'linear-gradient(135deg, #D4B038, #B8942A)', color: '#3D0F22', boxShadow: '0 4px 16px rgba(212,176,56,0.4)' }}
                    >
                      Submit
                    </motion.button>
                  </div>
                )}
              </div>
            </div>

            {submitError && (
              <div className="mt-3 text-center text-sm font-semibold" style={{ color: '#B91C1C' }}>
                {submitError}
              </div>
            )}

            <div className="mt-5 text-center">
              <button
                onClick={() => navigate(`/tools/writing-analyser/task/${encodeURIComponent(slug)}`)}
                className="text-sm font-semibold flex items-center gap-1.5 mx-auto"
                style={{ color: '#8B6B7A' }}
              >
                <ArrowLeft className="w-4 h-4" /> Back to questions
              </button>
            </div>
          </>
        )}
      </div>

      <AnimatePresence>
        {isSubmitting && <AnalysingScreen taskNumber={activeTask?.taskNumber} taskType={activeTask?.taskType} />}
      </AnimatePresence>
    </div>
  );
}

function WritingAnalyserWriteEssayFallback() {
  return (
    <div className="min-h-screen flex items-center justify-center" style={{ background: '#FAF5F0' }}>
      <Loader2 className="w-8 h-8 animate-spin" style={{ color: '#4A1429' }} />
    </div>
  );
}

export default function WritingAnalyserWriteEssayPage({ params }) {
  return (
    <Suspense fallback={<WritingAnalyserWriteEssayFallback />}>
      <WritingAnalyserWriteEssayContent params={params} />
    </Suspense>
  );
}

const ANALYSIS_MESSAGES = [
  'Reading your writing carefully...',
  'Checking grammar and accuracy...',
  'Evaluating vocabulary range...',
  'Assessing coherence and cohesion...',
  'Calculating your IELTS band score...',
  'Preparing your detailed feedback...',
];

function AnalysingScreen({ taskNumber, taskType }) {
  const [msgIdx, setMsgIdx] = useState(0);
  const [dotCount, setDotCount] = useState(0);

  useEffect(() => {
    const msgTimer = setInterval(() => setMsgIdx((i) => (i + 1) % ANALYSIS_MESSAGES.length), 2200);
    const dotTimer = setInterval(() => setDotCount((d) => (d + 1) % 4), 500);
    return () => {
      clearInterval(msgTimer);
      clearInterval(dotTimer);
    };
  }, []);

  const dots = '.'.repeat(dotCount);
  const label = (taskNumber || '').toLowerCase().includes('task 1')
    ? (taskType || '').toLowerCase().includes('academic') ? 'Report' : 'Letter'
    : 'Essay';

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-50 flex items-center justify-center overflow-hidden"
      style={{ background: 'linear-gradient(135deg, #2D0A18 0%, #4A1429 50%, #1A0610 100%)' }}
    >
      <div className="relative z-10 flex flex-col items-center text-center px-6 max-w-lg">
        <div className="relative mb-8">
          <motion.div
            className="w-28 h-28 rounded-full border-4"
            style={{ borderColor: 'rgba(212,176,56,0.2)', borderTopColor: '#D4B038' }}
            animate={{ rotate: 360 }}
            transition={{ repeat: Infinity, duration: 2, ease: 'linear' }}
          />
          <motion.div
            className="absolute inset-3 rounded-full border-2"
            style={{ borderColor: 'rgba(212,176,56,0.1)', borderBottomColor: 'rgba(212,176,56,0.5)' }}
            animate={{ rotate: -360 }}
            transition={{ repeat: Infinity, duration: 3, ease: 'linear' }}
          />
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-12 h-12 rounded-full flex items-center justify-center"
              style={{ background: 'rgba(212,176,56,0.15)', border: '1px solid rgba(212,176,56,0.3)' }}>
              <PenLine className="w-5 h-5" style={{ color: '#D4B038' }} />
            </div>
          </div>
        </div>

        <div className="text-xs font-black uppercase tracking-widest mb-3" style={{ color: 'rgba(212,176,56,0.6)' }}>
          Cambridge Veritas - AI Examiner
        </div>

        <h2 className="text-3xl font-black text-white mb-2 leading-tight">
          Analysing Your {label}
        </h2>

        <div className="h-8 mb-6 flex items-center">
          <motion.p
            key={msgIdx}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            transition={{ duration: 0.4 }}
            className="text-base font-semibold"
            style={{ color: 'rgba(255,255,255,0.65)' }}
          >
            {ANALYSIS_MESSAGES[msgIdx]}{dots}
          </motion.p>
        </div>

        <div className="w-64 h-1.5 rounded-full overflow-hidden mb-8" style={{ background: 'rgba(255,255,255,0.08)' }}>
          <motion.div
            className="h-full rounded-full"
            style={{ background: 'linear-gradient(90deg, #B8942A, #D4B038, #F0C84A)' }}
            animate={{ x: ['-100%', '200%'] }}
            transition={{ repeat: Infinity, duration: 1.8, ease: 'easeInOut' }}
          />
        </div>

        <div className="flex flex-wrap gap-2 justify-center">
          {['Task Achievement', 'Coherence', 'Lexical Resource', 'Grammar'].map((chip) => (
            <motion.div
              key={chip}
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: [0.4, 1, 0.4] }}
              transition={{ repeat: Infinity, duration: 2 }}
              className="px-3 py-1.5 rounded-full text-xs font-bold"
              style={{ background: 'rgba(212,176,56,0.1)', border: '1px solid rgba(212,176,56,0.25)', color: 'rgba(212,176,56,0.8)' }}
            >
              {chip}
            </motion.div>
          ))}
        </div>
      </div>
    </motion.div>
  );
}
