'use client';

import { FORMATS, TONES } from '@/lib/mock-data';
import { AnimatePresence, motion } from 'framer-motion';
import { ChevronLeft, ChevronRight, Search, Sparkles, Target } from 'lucide-react';
import { useState } from 'react';
import { FormatRadio } from './FormatRadio';
import { StepProgressBar } from './StepProgressBar';
import { TagInput } from './TagInput';

interface WizardParams {
  keyword: string;
  competitorUrl: string;
  format: string;
  wordCount: number;
  tone: string;
  customTone: string;
  intent: 'informational' | 'commercial' | 'transactional';
  audience: string;
  secondaryKeywords: string[];
}

interface WorkflowWizardProps {
  onGenerate: (params: WizardParams) => void;
}

const INTENTS = [
  {
    id: 'informational',
    label: 'Informationnel',
    desc: 'Répondre à une question, éduquer',
    icon: Search,
  },
  { id: 'commercial', label: 'Commercial', desc: 'Comparer, convaincre, orienter', icon: Target },
  {
    id: 'transactional',
    label: 'Transactionnel',
    desc: 'Déclencher un achat ou une action',
    icon: Sparkles,
  },
] as const;

const AUDIENCES = ['Grand public', 'Experts', 'Débutants', 'Décideurs B2B'];

const TONE_EXAMPLES: Record<string, string> = {
  'Professionnel, expert':
    'Notre analyse démontre une corrélation directe entre la matière et la durabilité.',
  'Chaleureux, proche':
    'On vous dit tout sur les baskets qui font du bien, à vous et à la planète.',
  'Éditorial, inspiration': "Derrière chaque paire, une histoire de savoir-faire et d'engagement.",
  'Direct, commercial': "Jusqu'à 40% plus durable. Zéro compromis sur le style.",
  'Pédagogique, factuel':
    'Le cuir vegan est fabriqué à partir de matières synthétiques ou végétales.',
  'Premium, sophistiqué':
    "L'excellence se reconnaît dans les détails — et dans les choix que l'on fait.",
};

const SLIDE_VARIANTS = {
  enter: (dir: number) => ({ x: dir > 0 ? 40 : -40, opacity: 0 }),
  center: { x: 0, opacity: 1 },
  exit: (dir: number) => ({ x: dir > 0 ? -40 : 40, opacity: 0 }),
};

export function WorkflowWizard({ onGenerate }: WorkflowWizardProps) {
  const [step, setStep] = useState(0);
  const [dir, setDir] = useState(1);
  const [serpLoading, setSerpLoading] = useState(false);
  const [serpDone, setSerpDone] = useState(false);
  const [serpLines, setSerpLines] = useState<string[]>([]);

  const [params, setParams] = useState<WizardParams>({
    keyword: 'baskets éthiques hiver',
    competitorUrl: '',
    format: 'article',
    wordCount: 1500,
    tone: 'Chaleureux, proche',
    customTone: '',
    intent: 'commercial',
    audience: 'Grand public',
    secondaryKeywords: ['cuir vegan', 'basket éthique', 'mode responsable'],
  });

  function update<K extends keyof WizardParams>(key: K, value: WizardParams[K]) {
    setParams((p) => ({ ...p, [key]: value }));
  }

  function goNext() {
    setDir(1);
    setStep((s) => Math.min(s + 1, 4));
  }

  function goPrev() {
    setDir(-1);
    setStep((s) => Math.max(s - 1, 0));
  }

  function runSerp() {
    if (serpLoading || serpDone) return;
    setSerpLoading(true);
    setSerpLines([]);
    const lines = [
      'Top 10 concurrents analysés',
      'Volume : 8 900/mois',
      'Difficulté : 42',
      'Intention : commerciale',
    ];
    lines.forEach((line, i) => {
      setTimeout(
        () => {
          setSerpLines((prev) => [...prev, line]);
          if (i === lines.length - 1) {
            setSerpLoading(false);
            setSerpDone(true);
          }
        },
        400 + i * 320
      );
    });
  }

  const selectedFormat = FORMATS.find((f) => f.id === params.format) ?? FORMATS[0];
  const tokenEstimate = Math.round(
    (params.wordCount / selectedFormat.avgWords) * selectedFormat.avgTokens
  );

  return (
    <div className="max-w-2xl mx-auto">
      <StepProgressBar currentStep={step} />

      <div className="overflow-hidden">
        <AnimatePresence custom={dir} mode="wait">
          <motion.div
            key={step}
            custom={dir}
            variants={SLIDE_VARIANTS}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{ duration: 0.28, ease: 'easeInOut' }}
          >
            {step === 0 && (
              <StepCard title="Sujet & mot-clé cible">
                <label htmlFor="keyword" className="block text-[12px] text-text-dim mb-1.5">
                  Mot-clé principal
                </label>
                <input
                  id="keyword"
                  type="text"
                  value={params.keyword}
                  onChange={(e) => update('keyword', e.target.value)}
                  className="w-full px-3 py-2.5 text-[13px] bg-bg border border-border rounded-lg focus:outline-none focus:border-border-bright text-text placeholder:text-text-dimmer mb-4"
                  placeholder="Ex : baskets éthiques hiver"
                />

                <label htmlFor="competitorUrl" className="block text-[12px] text-text-dim mb-1.5">
                  URL concurrent (facultatif)
                </label>
                <input
                  id="competitorUrl"
                  type="text"
                  value={params.competitorUrl}
                  onChange={(e) => update('competitorUrl', e.target.value)}
                  className="w-full px-3 py-2.5 text-[13px] bg-bg border border-border rounded-lg focus:outline-none focus:border-border-bright text-text placeholder:text-text-dimmer mb-5"
                  placeholder="https://concurrent.com/article"
                />

                <button
                  type="button"
                  onClick={runSerp}
                  disabled={serpLoading}
                  className="flex items-center gap-2 px-4 py-2.5 rounded-lg bg-accent/15 border border-accent/30 text-accent-light text-[13px] font-medium hover:bg-accent/25 transition-colors disabled:opacity-60"
                >
                  <Search className="w-3.5 h-3.5" strokeWidth={2} />
                  {serpLoading
                    ? 'Analyse en cours...'
                    : serpDone
                      ? 'SERP analysés'
                      : 'Analyser les SERP'}
                </button>

                <AnimatePresence>
                  {(serpLoading || serpDone) && (
                    <motion.div
                      initial={{ opacity: 0, height: 0 }}
                      animate={{ opacity: 1, height: 'auto' }}
                      exit={{ opacity: 0, height: 0 }}
                      className="mt-4 p-4 bg-bg border border-border rounded-xl overflow-hidden"
                    >
                      {serpLoading && serpLines.length === 0 && (
                        <div className="space-y-2">
                          {[80, 60, 70, 50].map((w, i) => (
                            <div
                              key={i}
                              className={`h-3 rounded shimmer`}
                              style={{ width: `${w}%` }}
                            />
                          ))}
                        </div>
                      )}
                      <div className="space-y-2">
                        {serpLines.map((line, i) => (
                          <motion.div
                            key={i}
                            initial={{ opacity: 0, x: -8 }}
                            animate={{ opacity: 1, x: 0 }}
                            className="flex items-center gap-2 text-[12.5px] text-text-dim"
                          >
                            <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 flex-shrink-0" />
                            {line}
                          </motion.div>
                        ))}
                        {serpLoading && (
                          <div className="h-3 rounded shimmer" style={{ width: '60%' }} />
                        )}
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </StepCard>
            )}

            {step === 1 && (
              <StepCard title="Format & longueur">
                <p className="text-[12.5px] text-text-dim mb-4">
                  Choisissez le format du contenu à générer.
                </p>
                <FormatRadio
                  selected={params.format}
                  onSelect={(id) => update('format', id)}
                  wordCount={params.wordCount}
                />

                <div className="mt-6">
                  <div className="flex items-center justify-between mb-2">
                    <label htmlFor="wordCount" className="text-[12px] text-text-dim">
                      Longueur cible
                    </label>
                    <div className="flex items-center gap-2 text-[12px] font-mono">
                      <span className="text-text">{params.wordCount.toLocaleString()} mots</span>
                      <span className="text-text-dimmer">·</span>
                      <span className="text-accent-light">
                        ~{tokenEstimate.toLocaleString()} tokens
                      </span>
                    </div>
                  </div>
                  <input
                    id="wordCount"
                    type="range"
                    min={500}
                    max={5000}
                    step={100}
                    value={params.wordCount}
                    onChange={(e) => update('wordCount', Number(e.target.value))}
                    className="w-full accent-accent h-1.5 cursor-pointer"
                  />
                  <div className="flex justify-between text-[10.5px] text-text-dimmer mt-1">
                    <span>500</span>
                    <span>5 000</span>
                  </div>
                </div>
              </StepCard>
            )}

            {step === 2 && (
              <StepCard title="Ton de voix">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mb-5">
                  {TONES.map((tone) => {
                    const isSelected = params.tone === tone;
                    return (
                      <button
                        key={tone}
                        type="button"
                        onClick={() => update('tone', tone)}
                        className={`text-left p-3.5 rounded-xl border transition-all ${
                          isSelected
                            ? 'bg-accent/10 border-accent/50'
                            : 'bg-bg border-border hover:border-border-bright hover:bg-bg-card-hover'
                        }`}
                      >
                        <div
                          className={`text-[12.5px] font-semibold mb-1 ${isSelected ? 'text-text' : 'text-text-dim'}`}
                        >
                          {tone}
                        </div>
                        <div className="text-[11px] text-text-dimmer italic leading-relaxed">
                          {TONE_EXAMPLES[tone]}
                        </div>
                      </button>
                    );
                  })}
                </div>
                <label htmlFor="customTone" className="block text-[12px] text-text-dim mb-1.5">
                  Ou décris ton ton en 2-3 mots
                </label>
                <textarea
                  id="customTone"
                  value={params.customTone}
                  onChange={(e) => update('customTone', e.target.value)}
                  placeholder="Ex : taquin, expert, nerveux..."
                  rows={2}
                  className="w-full px-3 py-2.5 text-[13px] bg-bg border border-border rounded-lg focus:outline-none focus:border-border-bright text-text placeholder:text-text-dimmer resize-none"
                />
              </StepCard>
            )}

            {step === 3 && (
              <StepCard title="Intention & audience">
                <p className="text-[12px] text-text-dim mb-3">Intention de recherche</p>
                <div className="grid grid-cols-3 gap-3 mb-6">
                  {INTENTS.map(({ id, label, desc, icon: Icon }) => {
                    const isSelected = params.intent === id;
                    return (
                      <button
                        key={id}
                        type="button"
                        onClick={() => update('intent', id)}
                        className={`text-center p-3.5 rounded-xl border transition-all ${
                          isSelected
                            ? 'bg-accent/10 border-accent/50'
                            : 'bg-bg border-border hover:border-border-bright hover:bg-bg-card-hover'
                        }`}
                      >
                        <Icon
                          className={`w-5 h-5 mx-auto mb-2 ${isSelected ? 'text-accent-light' : 'text-text-dimmer'}`}
                          strokeWidth={1.75}
                        />
                        <div
                          className={`text-[12px] font-semibold mb-1 ${isSelected ? 'text-text' : 'text-text-dim'}`}
                        >
                          {label}
                        </div>
                        <div className="text-[10.5px] text-text-dimmer leading-tight">{desc}</div>
                      </button>
                    );
                  })}
                </div>

                <label htmlFor="audience" className="block text-[12px] text-text-dim mb-1.5">
                  Audience cible
                </label>
                <select
                  id="audience"
                  value={params.audience}
                  onChange={(e) => update('audience', e.target.value)}
                  className="w-full px-3 py-2.5 text-[13px] bg-bg border border-border rounded-lg focus:outline-none focus:border-border-bright text-text mb-5"
                >
                  {AUDIENCES.map((a) => (
                    <option key={a} value={a}>
                      {a}
                    </option>
                  ))}
                </select>

                <p className="block text-[12px] text-text-dim mb-1.5">
                  Mots-clés secondaires{' '}
                  <span className="text-text-dimmer">(Entrée pour ajouter)</span>
                </p>
                <TagInput
                  tags={params.secondaryKeywords}
                  onChange={(tags) => update('secondaryKeywords', tags)}
                />
              </StepCard>
            )}

            {step === 4 && (
              <StepCard title="Récap & lancement">
                <div className="space-y-3 mb-6">
                  <RecapRow label="Mot-clé" value={params.keyword} />
                  <RecapRow
                    label="Format"
                    value={FORMATS.find((f) => f.id === params.format)?.label ?? params.format}
                  />
                  <RecapRow
                    label="Longueur"
                    value={`${params.wordCount.toLocaleString()} mots (~${tokenEstimate.toLocaleString()} tokens)`}
                  />
                  <RecapRow label="Ton" value={params.customTone || params.tone} />
                  <RecapRow
                    label="Intention"
                    value={
                      {
                        informational: 'Informationnel',
                        commercial: 'Commercial',
                        transactional: 'Transactionnel',
                      }[params.intent]
                    }
                  />
                  <RecapRow label="Audience" value={params.audience} />
                  <RecapRow
                    label="Mots-clés sec."
                    value={params.secondaryKeywords.join(', ') || '—'}
                  />
                </div>

                <div className="grid grid-cols-3 gap-3 mb-6">
                  {[
                    { label: 'Temps estimé', value: '~18 s' },
                    { label: 'Tokens estimés', value: `~${tokenEstimate.toLocaleString()}` },
                    { label: 'Score SEO projeté', value: '88/100' },
                  ].map(({ label, value }) => (
                    <div
                      key={label}
                      className="p-3 bg-bg border border-border rounded-xl text-center"
                    >
                      <div className="text-[11px] text-text-dimmer mb-1">{label}</div>
                      <div className="text-[15px] font-semibold text-accent-light font-mono">
                        {value}
                      </div>
                    </div>
                  ))}
                </div>

                <motion.button
                  type="button"
                  whileTap={{ scale: 0.98 }}
                  onClick={() => onGenerate(params)}
                  className="w-full flex items-center justify-center gap-2.5 py-3.5 rounded-xl bg-gradient-to-r from-accent to-cyan-500 text-white text-[14px] font-semibold shadow-[0_0_24px_rgba(99,102,241,0.35)] hover:shadow-[0_0_32px_rgba(99,102,241,0.5)] transition-shadow"
                >
                  <Sparkles className="w-4.5 h-4.5" strokeWidth={2} />
                  Générer le contenu
                </motion.button>
              </StepCard>
            )}
          </motion.div>
        </AnimatePresence>
      </div>

      {/* Nav buttons */}
      <div className="flex items-center justify-between mt-6">
        <button
          type="button"
          onClick={goPrev}
          disabled={step === 0}
          className="flex items-center gap-1.5 px-4 py-2 rounded-lg border border-border text-[13px] text-text-dim hover:text-text hover:border-border-bright transition-all disabled:opacity-30 disabled:cursor-not-allowed"
        >
          <ChevronLeft className="w-4 h-4" />
          Précédent
        </button>

        {step < 4 && (
          <button
            type="button"
            onClick={goNext}
            className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-accent/15 border border-accent/30 text-accent-light text-[13px] font-medium hover:bg-accent/25 transition-colors"
          >
            Suivant
            <ChevronRight className="w-4 h-4" />
          </button>
        )}
      </div>
    </div>
  );
}

function StepCard({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="bg-bg-card border border-border rounded-2xl p-6">
      <h2 className="text-[16px] font-semibold text-text mb-5">{title}</h2>
      {children}
    </div>
  );
}

function RecapRow({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex items-start justify-between gap-4 py-2 border-b border-border last:border-0">
      <span className="text-[12px] text-text-dimmer shrink-0">{label}</span>
      <span className="text-[12.5px] text-text text-right">{value}</span>
    </div>
  );
}
