'use client';

import { AnimatePresence, motion } from 'framer-motion';
import {
  AlertTriangle,
  Archive,
  Bold,
  CheckCircle,
  Code,
  Heading2,
  Heading3,
  Italic,
  Lightbulb,
  Link,
  List,
  Quote,
  RotateCcw,
  Trash2,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

const INITIAL_CONTENT = `<h1>Comment choisir des baskets éthiques pour l'hiver : le guide complet</h1>

<h2>Pourquoi opter pour des baskets éthiques cet hiver ?</h2>

<p>Les baskets éthiques ne se résument pas à un argument marketing. Elles représentent un choix de consommation aligné avec des valeurs concrètes : réduction de l'empreinte carbone, conditions de travail équitables, et matières issues de filières traçables. En hiver, la question se pose avec encore plus d'acuité.</p>

<p>Les marques pionnières comme Veja, Nat-2 ou Flamingos Life ont démontré qu'il est possible de concilier performance technique et engagement environnemental. Leurs collections hiver intègrent des doublures en laine recyclée, des semelles en caoutchouc naturel et des tiges en cuir vegan certifié.</p>

<h2>Comment évaluer la durabilité d'une paire ?</h2>

<p>Quelques critères simples permettent de faire le tri. Vérifiez d'abord les certifications (GOTS, B Corp, Oeko-Tex). Ensuite, regardez la composition : un cuir vegan de qualité dure autant qu'un cuir animal avec un entretien adapté.</p>

<p>La mode responsable n'est pas une tendance passagère. C'est une réorientation structurelle du marché, accélérée par une génération de consommateurs qui veulent savoir ce qu'ils achètent et pourquoi.</p>`;

interface Suggestion {
  id: string;
  type: 'warning' | 'tip' | 'ok';
  text: string;
}

const INITIAL_SUGGESTIONS: Suggestion[] = [
  {
    id: 's1',
    type: 'warning',
    text: "Ajoute le mot-clé secondaire 'mode responsable' dans le 2e H2.",
  },
  {
    id: 's2',
    type: 'tip',
    text: "La méta description fait 155 caractères — ajoute 5-10 caractères pour l'optimal.",
  },
  {
    id: 's3',
    type: 'tip',
    text: "Internal link vers la fiche produit 'Sneaker Mistral Ivoire' recommandé.",
  },
  { id: 's4', type: 'ok', text: 'Densité du mot-clé principal correcte (1,4%).' },
];

const WORD_COUNT = 218;
const READ_TIME = Math.ceil(WORD_COUNT / 200);

interface SeoRingProps {
  score: number;
}

function SeoRing({ score }: SeoRingProps) {
  const radius = 28;
  const circ = 2 * Math.PI * radius;
  const offset = circ - (score / 100) * circ;
  const color = score >= 85 ? '#34d399' : score >= 70 ? '#fbbf24' : '#f87171';

  return (
    <div className="relative w-20 h-20">
      <svg
        className="w-20 h-20 -rotate-90"
        viewBox="0 0 72 72"
        role="img"
        aria-label={`Score SEO : ${score}/100`}
      >
        <circle cx="36" cy="36" r={radius} fill="none" stroke="#1a1a2e" strokeWidth="6" />
        <motion.circle
          cx="36"
          cy="36"
          r={radius}
          fill="none"
          stroke={color}
          strokeWidth="6"
          strokeLinecap="round"
          strokeDasharray={circ}
          initial={{ strokeDashoffset: circ }}
          animate={{ strokeDashoffset: offset }}
          transition={{ duration: 1.2, ease: 'easeOut' }}
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className="text-[18px] font-bold text-text leading-none">{score}</span>
        <span className="text-[9px] text-text-dimmer uppercase tracking-wider">/100</span>
      </div>
    </div>
  );
}

const TOOLBAR_ACTIONS = [
  { icon: Bold, label: 'Gras' },
  { icon: Italic, label: 'Italique' },
  { icon: Heading2, label: 'H2' },
  { icon: Heading3, label: 'H3' },
  { icon: Link, label: 'Lien' },
  { icon: List, label: 'Liste' },
  { icon: Quote, label: 'Citation' },
  { icon: Code, label: 'Code' },
];

export function ContentEditor({ onReset }: { onReset: () => void }) {
  const [suggestions, setSuggestions] = useState<Suggestion[]>(INITIAL_SUGGESTIONS);
  const [meta, setMeta] = useState(
    "Découvrez comment choisir des baskets éthiques pour l'hiver : matières durables, certifications, meilleures marques responsables."
  );
  const editorRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (editorRef.current) {
      editorRef.current.innerHTML = INITIAL_CONTENT;
    }
  }, []);

  function removeSuggestion(id: string) {
    setSuggestions((prev) => prev.filter((s) => s.id !== id));
  }

  const metaLen = meta.length;

  function SuggestionIcon({ type }: { type: Suggestion['type'] }) {
    if (type === 'warning')
      return (
        <AlertTriangle
          className="w-3.5 h-3.5 text-amber-400 flex-shrink-0 mt-0.5"
          strokeWidth={2}
        />
      );
    if (type === 'tip')
      return (
        <Lightbulb className="w-3.5 h-3.5 text-accent-light flex-shrink-0 mt-0.5" strokeWidth={2} />
      );
    return (
      <CheckCircle className="w-3.5 h-3.5 text-emerald-400 flex-shrink-0 mt-0.5" strokeWidth={2} />
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="grid grid-cols-1 lg:grid-cols-[1fr_300px] gap-6"
    >
      {/* Editor column */}
      <div className="flex flex-col gap-0">
        {/* Toolbar */}
        <div className="sticky top-14 z-10 flex items-center gap-1 flex-wrap px-4 py-2.5 bg-bg-card border border-border rounded-t-2xl border-b-0">
          {TOOLBAR_ACTIONS.map(({ icon: Icon, label }) => (
            <button
              key={label}
              type="button"
              title={label}
              className="p-2 rounded-lg text-text-dim hover:text-text hover:bg-bg-card-hover transition-colors"
            >
              <Icon className="w-3.5 h-3.5" strokeWidth={1.75} />
            </button>
          ))}
        </div>

        {/* Editable area */}
        <div
          ref={editorRef}
          contentEditable
          suppressContentEditableWarning
          className={[
            'min-h-[480px] px-6 py-5 bg-bg-card border border-border rounded-b-2xl',
            'text-[14px] leading-relaxed text-text outline-none',
            'focus:border-border-bright',
            '[&_h1]:text-[22px] [&_h1]:font-bold [&_h1]:text-text [&_h1]:mb-4 [&_h1]:leading-snug',
            '[&_h2]:text-[17px] [&_h2]:font-semibold [&_h2]:text-text [&_h2]:mt-6 [&_h2]:mb-3',
            '[&_p]:text-text-dim [&_p]:mb-3 [&_p]:leading-7',
          ].join(' ')}
        />
      </div>

      {/* SEO sidebar */}
      <div className="space-y-4">
        {/* Score */}
        <div className="bg-bg-card border border-border rounded-2xl p-5">
          <h3 className="text-[12px] text-text-dimmer uppercase tracking-wider mb-4">Score SEO</h3>
          <div className="flex items-center gap-4">
            <SeoRing score={89} />
            <div>
              <div className="text-[13px] font-semibold text-emerald-400 mb-0.5">Très bon</div>
              <div className="text-[11px] text-text-dimmer leading-relaxed">
                3 optimisations possibles pour atteindre 95+
              </div>
            </div>
          </div>
        </div>

        {/* Suggestions */}
        <div className="bg-bg-card border border-border rounded-2xl p-5">
          <h3 className="text-[12px] text-text-dimmer uppercase tracking-wider mb-4">
            Suggestions IA
          </h3>
          <div className="space-y-3">
            <AnimatePresence>
              {suggestions.map((s) => (
                <motion.div
                  key={s.id}
                  layout
                  initial={{ opacity: 0, height: 0 }}
                  animate={{ opacity: 1, height: 'auto' }}
                  exit={{ opacity: 0, height: 0, marginBottom: 0 }}
                  transition={{ duration: 0.22 }}
                  className="overflow-hidden"
                >
                  <div className="flex items-start gap-2.5 p-3 bg-bg border border-border rounded-xl">
                    <SuggestionIcon type={s.type} />
                    <div className="flex-1 min-w-0">
                      <p className="text-[11.5px] text-text-dim leading-snug">{s.text}</p>
                      <button
                        type="button"
                        onClick={() => removeSuggestion(s.id)}
                        className="mt-2 text-[10.5px] text-accent-light hover:text-accent transition-colors font-medium"
                      >
                        Appliquer
                      </button>
                    </div>
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>
            {suggestions.length === 0 && (
              <p className="text-[12px] text-text-dimmer text-center py-3">
                Toutes les suggestions ont été appliquées.
              </p>
            )}
          </div>
        </div>

        {/* Stats */}
        <div className="bg-bg-card border border-border rounded-2xl p-5">
          <h3 className="text-[12px] text-text-dimmer uppercase tracking-wider mb-4">
            Statistiques
          </h3>
          <div className="space-y-2.5">
            {[
              { label: 'Mots', value: WORD_COUNT.toLocaleString() },
              { label: 'Temps de lecture', value: `${READ_TIME} min` },
              { label: 'Score lisibilité', value: '72 / Flesch' },
              { label: 'Densité mot-clé', value: '1,4%' },
              { label: 'Liens internes', value: '1' },
            ].map(({ label, value }) => (
              <div key={label} className="flex items-center justify-between">
                <span className="text-[11.5px] text-text-dimmer">{label}</span>
                <span className="text-[12px] text-text font-mono">{value}</span>
              </div>
            ))}

            {/* Meta */}
            <div className="pt-2 border-t border-border">
              <div className="flex items-center justify-between mb-1.5">
                <span className="text-[11.5px] text-text-dimmer">Méta description</span>
                <span
                  className={`text-[11px] font-mono ${metaLen >= 150 && metaLen <= 165 ? 'text-emerald-400' : 'text-amber-400'}`}
                >
                  {metaLen} / 165
                </span>
              </div>
              <textarea
                value={meta}
                onChange={(e) => setMeta(e.target.value)}
                rows={3}
                className="w-full px-2.5 py-2 text-[11.5px] bg-bg border border-border rounded-lg focus:outline-none focus:border-border-bright text-text-dim resize-none"
              />
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="space-y-2">
          <button
            type="button"
            className="w-full py-2.5 rounded-xl bg-gradient-to-r from-accent to-cyan-500 text-white text-[13px] font-semibold hover:shadow-[0_0_20px_rgba(99,102,241,0.35)] transition-shadow"
          >
            <Archive className="w-3.5 h-3.5 inline mr-2" strokeWidth={2} />
            Valider et archiver
          </button>
          <button
            type="button"
            className="w-full py-2.5 rounded-xl border border-accent/40 text-accent-light text-[13px] font-medium hover:bg-accent/10 transition-colors"
          >
            <RotateCcw className="w-3.5 h-3.5 inline mr-2" strokeWidth={2} />
            Demander à l'IA de reformuler
          </button>
          <button
            type="button"
            onClick={onReset}
            className="w-full py-2.5 rounded-xl border border-red-500/30 text-red-400 text-[13px] font-medium hover:bg-red-500/10 transition-colors"
          >
            <Trash2 className="w-3.5 h-3.5 inline mr-2" strokeWidth={2} />
            Rejeter et recommencer
          </button>
        </div>
      </div>
    </motion.div>
  );
}
