'use client';

import React from 'react';
import { motion } from 'framer-motion';
import { useNavigate } from '@/lib/nextRouterAdapter';
import { appendRegionCurrencyToPath } from '@/lib/regionCurrencyLink';
import {
  Mic,
  ChevronRight,
  GraduationCap,
  Briefcase,
  TrendingUp,
  Sparkles,
  CreditCard,
  CheckCircle2,
  XCircle,
  MessageSquarePlus,
  Gift,
  Play,
  Crown,
  ArrowRight,
  Calendar,
  MessageCircle,
} from 'lucide-react';

const GOLD = '#D4B038';
const DARK = '#4A1429';

const features = [
  { icon: GraduationCap, color: '#4A1429', bg: '#FDF2F8', label: 'IELTS Band Prediction', sub: 'Predicted score after every session' },
  { icon: Mic, color: '#DC2626', bg: '#FEF2F2', label: 'Phoneme Analysis', sub: 'Find exactly which sounds to fix' },
  { icon: TrendingUp, color: '#059669', bg: '#ECFDF5', label: 'Week-by-Week Progress', sub: 'Watch yourself improve in real time' },
  { icon: Briefcase, color: '#1D4ED8', bg: '#EFF6FF', label: 'Grammar & Vocabulary AI', sub: 'Smart corrections after every answer' },
];

const purposeConfig = {
  ielts: { label: 'IELTS Speaking', icon: GraduationCap, color: '#4A1429', bg: '#FDF2F8' },
  business: { label: 'Business English', icon: Briefcase, color: '#1E3A5F', bg: '#EFF6FF' },
  general: { label: 'General English', icon: MessageCircle, color: '#064E3B', bg: '#ECFDF5' },
};

const skillColors = [
  { key: 'pronunciation', color: '#EF4444' },
  { key: 'intonation', color: '#D4B038' },
  { key: 'fluency', color: '#3B82F6' },
  { key: 'grammar', color: '#10B981' },
  { key: 'vocabulary', color: '#8B5CF6' },
];

function formatDate(isoStr) {
  if (!isoStr) return '-';
  return new Date(isoStr).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}

export default function TrialDashboard({
  user,
  onFeedbackOpen,
  exhausted = false,
  attemptsLeft = 1,
  attemptsTotal = 1,
  sessions = [],
  isLoadingSessions = false,
}) {
  const navigate = useNavigate();
  const noActivePlanPath = appendRegionCurrencyToPath('/tools/no-active-plan');
  const firstName = user?.first_name
    ? user.first_name
    : user?.full_name
      ? user.full_name.split(' ')[0]
      : null;

  const safeTotal = Math.max(1, Number(attemptsTotal) || 1);
  const safeLeft = Math.max(0, Math.min(safeTotal, Number(attemptsLeft) || 0));
  const completedPct = ((safeTotal - safeLeft) / safeTotal) * 100;
  const hasSessions = Array.isArray(sessions) && sessions.length > 0;

  const handleStartTest = () => {
    navigate('/tools/speech-analyser?step=purposes');
  };

  const handleUpgrade = () => {
    navigate(noActivePlanPath);
  };

  const handleFreeTrialPlanOpen = () => {
    navigate('/tools/active-plan');
  };

  const primaryCtaText = exhausted
    ? 'Choose Your Plan & Continue Learning'
    : 'Start Your Free AI Coaching Session';

  const primaryCtaAction = exhausted ? handleUpgrade : handleStartTest;
  const freeTrialCardClass = 'bg-white rounded-2xl border border-[#E5DDD5] shadow-sm p-4 text-left transition-all group relative overflow-hidden';
  const freeTrialCardContent = (
    <>
      <div
        className="absolute top-0 right-0 w-28 h-28 rounded-full pointer-events-none opacity-20"
        style={{ background: 'radial-gradient(circle, #10B98140 0%, transparent 70%)', transform: 'translate(30%,-30%)' }}
      />
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-3 min-w-0">
          <div className={`w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 ${exhausted ? 'bg-gray-100' : 'bg-emerald-50'}`}>
            <Crown className={`w-4 h-4 ${exhausted ? 'text-gray-400' : 'text-emerald-600'}`} />
          </div>
          <div className="min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="font-extrabold text-[#4A1429] text-base leading-tight">Free Trial Plan</span>
              {exhausted ? (
                <span className="inline-flex items-center gap-1 text-[10px] font-bold text-red-600 bg-red-50 border border-red-100 px-2 py-0.5 rounded-full">
                  <XCircle className="w-2.5 h-2.5" /> Exhausted
                </span>
              ) : (
                <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-600 bg-emerald-50 border border-emerald-100 px-2 py-0.5 rounded-full">
                  <CheckCircle2 className="w-2.5 h-2.5" /> Active
                </span>
              )}
            </div>
            <div className="text-[11px] text-gray-400 mt-0.5">
              {exhausted ? 'Plan completed' : 'Tap to view your plan'}
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2 flex-shrink-0">
          <div className="text-right bg-[#FAF5F0] rounded-xl px-3 py-2 border border-[#E5DDD5]">
            <div className="flex items-baseline gap-1">
              <span className={`text-lg font-extrabold leading-none ${exhausted ? 'text-gray-400' : 'text-[#4A1429]'}`}>
                {safeLeft}
              </span>
              <span className="text-[11px] text-gray-400">/ {safeTotal}</span>
            </div>
            <div className="text-[10px] text-gray-400 mt-0.5">sessions left</div>
            <div className="w-16 h-1 bg-gray-200 rounded-full overflow-hidden mt-1.5">
              <div
                className="h-full rounded-full"
                style={{ width: `${completedPct}%`, backgroundColor: GOLD }}
              />
            </div>
          </div>
          {!exhausted && (
            <ChevronRight className="w-4 h-4 text-gray-300 group-hover:text-[#D4B038] transition-colors" />
          )}
        </div>
      </div>
    </>
  );

  return (
    <div className="max-w-5xl mx-auto px-4 py-6 space-y-5">
      <motion.div
        initial={{ opacity: 0, y: 16 }}
        animate={{ opacity: 1, y: 0 }}
        className="relative bg-gradient-to-br from-[#4A1429] via-[#5A1839] to-[#3A0F20] rounded-2xl p-5 sm:p-8 overflow-hidden"
      >
        <div
          className="absolute inset-0 opacity-[0.06]"
          style={{ backgroundImage: 'radial-gradient(circle, #fff 1px, transparent 1px)', backgroundSize: '24px 24px' }}
        />
        <div
          className="absolute top-0 right-0 w-48 h-48 rounded-full pointer-events-none"
          style={{ background: 'radial-gradient(circle, rgba(212,176,56,0.15) 0%, transparent 70%)', transform: 'translate(20%,-20%)' }}
        />

        <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 mb-2">
              <Sparkles className="w-4 h-4 text-[#D4B038]" />
              <span className="text-[#D4B038] text-xs font-bold uppercase tracking-widest">Your Dashboard</span>
            </div>
            <h1 className="text-xl sm:text-3xl font-extrabold text-white leading-tight">
              {exhausted
                ? (firstName ? `Welcome back, ${firstName}!` : 'Welcome back!')
                : (firstName ? `Welcome, ${firstName}!` : 'Welcome!')}
            </h1>
            <p className="text-white/50 text-sm mt-1">
              {exhausted
                ? 'Your free trial has been completed. Upgrade your plan to continue learning.'
                : 'You have 1 free trial session - start your AI coaching session below.'}
            </p>
          </div>

          <div className="flex items-center gap-3 bg-white/10 rounded-2xl px-4 py-3 flex-shrink-0">
            <div
              className="w-10 h-10 rounded-xl flex items-center justify-center"
              style={{ background: exhausted ? 'rgba(212,176,56,0.2)' : 'rgba(16,185,129,0.2)' }}
            >
              <Gift className={`w-5 h-5 ${exhausted ? 'text-[#D4B038]' : 'text-emerald-300'}`} />
            </div>
            <div>
              <div className={`font-extrabold text-sm ${exhausted ? 'text-[#D4B038]' : 'text-emerald-300'}`}>Free Trial</div>
              <div className={`text-xs ${exhausted ? 'text-red-300 font-bold' : 'text-white/40'}`}>
                {exhausted ? 'Plan Exhausted' : '1 session included'}
              </div>
            </div>
          </div>
        </div>
      </motion.div>

      <motion.div
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.05 }}
        className="grid grid-cols-1 sm:grid-cols-2 gap-3"
      >
        {exhausted ? (
          <div
            aria-disabled="true"
            className={`${freeTrialCardClass} opacity-75 cursor-not-allowed`}
            style={{ cursor: 'not-allowed' }}
          >
            {freeTrialCardContent}
          </div>
        ) : (
          <button
            onClick={handleFreeTrialPlanOpen}
            className={`${freeTrialCardClass} cursor-pointer hover:shadow-md hover:border-[#D4B038]`}
          >
            {freeTrialCardContent}
          </button>
        )}

        <button
          onClick={handleUpgrade}
          className="bg-white rounded-2xl border border-[#E5DDD5] shadow-sm p-4 text-left hover:shadow-md hover:border-[#D4B038] transition-all group relative overflow-hidden"
        >
          <div
            className="absolute top-0 right-0 w-28 h-28 rounded-full pointer-events-none opacity-20"
            style={{ background: 'radial-gradient(circle, #D4B03840 0%, transparent 70%)', transform: 'translate(30%,-30%)' }}
          />
          <div className="flex items-center justify-between gap-3 relative">
            <div className="flex items-center gap-3 min-w-0">
              <div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 bg-[#FFFBEB]">
                <CreditCard className="w-4 h-4 text-[#D4B038]" />
              </div>
              <div className="min-w-0">
                <div className="font-extrabold text-[#4A1429] text-base leading-tight">Upgrade Plan</div>
                <div className="text-[11px] text-gray-400 mt-0.5">Unlock unlimited AI sessions</div>
              </div>
            </div>
            <ChevronRight className="w-4 h-4 text-gray-300 group-hover:text-[#D4B038] transition-colors flex-shrink-0" />
          </div>
        </button>
      </motion.div>

      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.15 }}>
        <button
          onClick={primaryCtaAction}
          className="w-full font-extrabold py-4 sm:py-5 rounded-2xl text-base transition-all flex items-center justify-center gap-3 shadow-lg bg-gradient-to-r from-[#D4B038] to-[#C9A830] hover:from-[#C9A830] hover:to-[#BFA030] text-[#4A1429] hover:scale-[1.01]"
        >
          <Mic className="w-5 h-5 text-[#4A1429]" />
          {primaryCtaText}
          <ArrowRight className="w-5 h-5" />
        </button>
      </motion.div>

      <motion.div initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-[#D4B038]" />
            <h2 className="text-base font-extrabold text-[#4A1429]">Recent Sessions</h2>
          </div>
          {hasSessions && (
            <button
              onClick={() => navigate('/tools/past-results')}
              className="text-xs font-bold text-[#D4B038] hover:text-[#BFA030] flex items-center gap-1 transition-colors bg-[#D4B038]/10 px-3 py-1.5 rounded-full"
            >
              View all <ChevronRight className="w-3.5 h-3.5" />
            </button>
          )}
        </div>

        <div className="bg-white rounded-2xl border border-[#E5DDD5] overflow-hidden">
          <div className="h-1.5 w-full" style={{ background: `linear-gradient(90deg, ${GOLD}, #C49A20)` }} />

          {isLoadingSessions ? (
            <div className="flex justify-center py-10">
              <div className="w-6 h-6 border-4 border-[#E5DDD5] border-t-[#4A1429] rounded-full animate-spin" />
            </div>
          ) : hasSessions ? (
            <div className="p-3 space-y-3">
              {sessions.slice(0, 5).map((session, index) => {
                const cfg = purposeConfig[session.purpose] || purposeConfig.general;
                const Icon = cfg.icon;
                const overall = session.scores?.overall ?? session.overall ?? null;
                const scoreNum = typeof overall === 'number' ? overall : null;
                const testLabel = session.test_label || cfg.label;
                return (
                  <motion.div
                    key={`${session.id || session.token || 'session'}-${index}`}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.25 + index * 0.06 }}
                    onClick={() => navigate('/tools/past-results')}
                    className="bg-white rounded-2xl border border-[#E5DDD5] shadow-sm hover:shadow-md hover:border-[#D4B038] transition-all cursor-pointer p-4"
                  >
                    <div className="flex items-center gap-4">
                      <div className="w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0" style={{ backgroundColor: cfg.bg }}>
                        <Icon className="w-5 h-5" style={{ color: cfg.color }} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-bold text-[#4A1429] text-sm mb-1">
                          {testLabel} - Part {session.part}
                        </div>
                        <div className="text-xs text-gray-400 flex items-center gap-1 mb-2">
                          <Calendar className="w-3 h-3" /> {formatDate(session.created_date)}
                        </div>
                        <div className="flex gap-1">
                          {skillColors.map((skill) => (
                            <div key={skill.key} className="flex-1">
                              <div className="h-2 rounded-full bg-gray-100 overflow-hidden">
                                <motion.div
                                  className="h-full rounded-full"
                                  style={{ backgroundColor: skill.color }}
                                  initial={{ width: 0 }}
                                  animate={{ width: `${session.scores?.[skill.key] ?? 0}%` }}
                                  transition={{ duration: 0.8, delay: 0.2 + index * 0.04 }}
                                />
                              </div>
                            </div>
                          ))}
                        </div>
                        <div className="flex gap-1 mt-1">
                          {skillColors.map((skill) => (
                            <div key={skill.key} className="flex-1 text-center">
                              <span className="text-[9px] font-bold" style={{ color: skill.color }}>
                                {session.scores?.[skill.key] ?? 0}
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        <div className="text-right">
                          {scoreNum !== null ? (
                            <>
                              <div className="text-2xl font-extrabold text-[#4A1429] leading-none">{scoreNum}</div>
                              <div className="text-[10px] text-gray-400 font-semibold">/ 100</div>
                            </>
                          ) : (
                            <div className="text-sm text-gray-400">-</div>
                          )}
                        </div>
                        <ChevronRight className="w-4 h-4 text-gray-300" />
                      </div>
                    </div>
                  </motion.div>
                );
              })}
            </div>
          ) : exhausted ? (
            <div className="p-8 sm:p-10 flex flex-col items-center text-center">
              <motion.div
                animate={{ scale: [1, 1.06, 1] }}
                transition={{ repeat: Infinity, duration: 2.8, ease: 'easeInOut' }}
                className="w-20 h-20 rounded-3xl flex items-center justify-center mb-5 shadow-lg"
                style={{ background: `linear-gradient(135deg, ${DARK}, #6B1E3D)` }}
              >
                <Mic className="w-9 h-9 text-white" />
              </motion.div>

              <h3 className="text-xl font-extrabold mb-2" style={{ color: DARK }}>
                Ready to continue your journey?
              </h3>
              <p className="text-gray-400 text-sm leading-relaxed max-w-sm mb-8">
                Upgrade to a paid plan to unlock AI coaching sessions and keep improving week by week.
              </p>

              <button
                onClick={handleUpgrade}
                className="flex items-center gap-2.5 font-extrabold py-3.5 px-8 rounded-2xl text-sm shadow-md"
                style={{ background: `linear-gradient(135deg, ${DARK}, #6B1E3D)`, color: GOLD }}
              >
                <Play className="w-4 h-4" />
                Choose Your Plan Now
              </button>
              <p className="text-gray-300 text-xs mt-3">3 plans available - cancel anytime</p>
            </div>
          ) : (
            <div className="p-8 sm:p-10 flex flex-col items-center text-center">
              <motion.div
                animate={{ scale: [1, 1.06, 1] }}
                transition={{ repeat: Infinity, duration: 2.8, ease: 'easeInOut' }}
                className="w-20 h-20 rounded-3xl flex items-center justify-center mb-5 shadow-lg"
                style={{ background: `linear-gradient(135deg, ${DARK}, #6B1E3D)` }}
              >
                <Mic className="w-9 h-9 text-white" />
              </motion.div>
              <h3 className="text-xl font-extrabold mb-2" style={{ color: DARK }}>
                Start your first session to see your results here
              </h3>
              <p className="text-gray-400 text-sm leading-relaxed max-w-sm mb-8">
                Your scores, skill breakdowns, IELTS prediction, and progress will appear here after your first session.
              </p>

              <div className="grid grid-cols-2 gap-3 w-full max-w-sm mb-8">
                {features.map((f, i) => {
                  const Icon = f.icon;
                  return (
                    <motion.div
                      key={i}
                      initial={{ opacity: 0, y: 8 }}
                      animate={{ opacity: 1, y: 0 }}
                      transition={{ delay: 0.4 + i * 0.08 }}
                      className="rounded-xl p-3 border border-[#E5DDD5] text-left flex items-start gap-2.5"
                    >
                      <div className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ backgroundColor: f.bg }}>
                        <Icon className="w-3.5 h-3.5" style={{ color: f.color }} />
                      </div>
                      <div>
                        <p className="text-[11px] font-extrabold leading-tight" style={{ color: DARK }}>{f.label}</p>
                        <p className="text-[10px] text-gray-400 mt-0.5 leading-tight">{f.sub}</p>
                      </div>
                    </motion.div>
                  );
                })}
              </div>

              <button
                onClick={handleStartTest}
                className="flex items-center gap-2.5 font-extrabold py-3.5 px-8 rounded-2xl text-sm shadow-md"
                style={{ background: `linear-gradient(135deg, ${DARK}, #6B1E3D)`, color: GOLD }}
              >
                <Play className="w-4 h-4" />
                Start my first session now
              </button>
              <p className="text-gray-300 text-xs mt-3">4 minutes - instant results</p>
            </div>
          )}
        </div>
      </motion.div>

      {onFeedbackOpen && (
        <button
          onClick={onFeedbackOpen}
          className="fixed bottom-6 right-5 z-40 flex items-center gap-2 bg-gradient-to-r from-[#4A1429] to-[#5A1839] hover:from-[#5A1839] hover:to-[#6B1E3D] text-[#D4B038] font-extrabold text-xs px-4 py-3 rounded-2xl shadow-2xl hover:scale-105 transition-all border border-[#D4B038]/30"
        >
          <MessageSquarePlus className="w-4 h-4" />
          <span className="hidden sm:inline">Share Feedback</span>
        </button>
      )}
    </div>
  );
}
