'use client';

import { useState, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import Link from 'next/link';
import {
  ArrowLeft, Palette, Loader2, Copy, Check, Sparkles, Eye,
  CheckCircle2, XCircle, Code2, Paintbrush
} from 'lucide-react';

/* ------------------------------------------------------------------ */
/*  Types matching API response                                        */
/* ------------------------------------------------------------------ */

interface PaletteColor {
  name: string;
  role: string;
  hex: string;
  hsl: string;
  rgb: string;
  usage: string;
}

interface ContrastPair {
  foreground: string;
  background: string;
  ratio: string;
  wcagAA: boolean;
  wcagAAA: boolean;
}

interface ColorSystem {
  brandName: string;
  description: string;
  colors: PaletteColor[];
  contrastPairs: ContrastPair[];
  cssVariables: string;
  tailwindConfig: string;
}

/* ------------------------------------------------------------------ */
/*  Prompt suggestions                                                  */
/* ------------------------------------------------------------------ */

const SUGGESTIONS = [
  'Cyberpunk neon nightclub',
  'Minimal Scandinavian furniture brand',
  'Luxury Italian coffee house',
  'Retro 80s synthwave arcade',
  'Earthy sustainable outdoor brand',
  'Futuristic medical technology',
  'Cozy indie bookshop',
  'Corporate fintech startup',
];

/* ------------------------------------------------------------------ */
/*  Helpers                                                             */
/* ------------------------------------------------------------------ */

function luminance(hex: string): number {
  const rgb = hex.replace('#', '').match(/.{2}/g);
  if (!rgb) return 0;
  const [r, g, b] = rgb.map((c) => {
    const v = parseInt(c, 16) / 255;
    return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

function textColorFor(hex: string): string {
  return luminance(hex) > 0.35 ? '#0f172a' : '#f8fafc';
}

/* ------------------------------------------------------------------ */
/*  Color swatch card                                                   */
/* ------------------------------------------------------------------ */

function SwatchCard({ color, index }: { color: PaletteColor; index: number }) {
  const [copied, setCopied] = useState(false);
  const textColor = textColorFor(color.hex);

  const copyHex = () => {
    navigator.clipboard.writeText(color.hex);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ delay: index * 0.05 }}
      className="group relative overflow-hidden rounded-xl border border-slate-700/40 hover:border-slate-600 transition-colors"
    >
      {/* Color block */}
      <button
        onClick={copyHex}
        className="w-full h-28 flex items-center justify-center relative cursor-pointer transition-transform active:scale-95"
        style={{ backgroundColor: color.hex }}
        title={`Click to copy ${color.hex}`}
      >
        <span className="text-lg font-mono font-bold opacity-80 group-hover:opacity-100 transition-opacity" style={{ color: textColor }}>
          {copied ? '✓ Copied' : color.hex}
        </span>
      </button>
      {/* Info */}
      <div className="bg-slate-900/80 p-3 space-y-1">
        <div className="flex items-center justify-between">
          <span className="text-sm font-semibold text-white">{color.name}</span>
        </div>
        <p className="text-xs text-slate-400 leading-snug">{color.role}</p>
        <div className="text-[10px] text-slate-500 font-mono">
          HSL({color.hsl}) · RGB({color.rgb})
        </div>
        <p className="text-[10px] text-slate-500">{color.usage}</p>
      </div>
    </motion.div>
  );
}

/* ------------------------------------------------------------------ */
/*  Code block with copy                                                */
/* ------------------------------------------------------------------ */

function CodeBlock({ title, code, lang }: { title: string; code: string; lang: string }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="border border-slate-700/50 rounded-lg overflow-hidden">
      <div className="flex items-center justify-between px-4 py-2 bg-slate-800/60 border-b border-slate-700/50">
        <span className="text-xs text-slate-400 font-medium">{title}</span>
        <button
          onClick={handleCopy}
          className="flex items-center gap-1.5 text-xs text-slate-400 hover:text-orange-300 transition-colors"
        >
          {copied ? <><Check className="w-3 h-3" /> Copied</> : <><Copy className="w-3 h-3" /> Copy</>}
        </button>
      </div>
      <pre className="p-4 text-xs text-slate-300 overflow-x-auto bg-slate-900/50">
        <code>{code}</code>
      </pre>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Preview panel                                                       */
/* ------------------------------------------------------------------ */

function PreviewPanel({ colors }: { colors: PaletteColor[] }) {
  const getHex = (name: string) => colors.find((c) => c.name.toLowerCase().includes(name.toLowerCase()))?.hex || '#666';

  const bg = getHex('background');
  const surface = getHex('surface');
  const primary = getHex('primary');
  const secondary = getHex('secondary');
  const textPrimary = getHex('text primary');
  const textSecondary = getHex('text secondary');
  const border = getHex('border');
  const success = getHex('success');

  return (
    <div className="rounded-xl overflow-hidden border border-slate-700/50" style={{ backgroundColor: bg }}>
      <div className="px-4 py-3 flex items-center gap-2" style={{ borderBottom: `1px solid ${border}` }}>
        <div className="flex gap-1.5">
          <div className="w-3 h-3 rounded-full bg-red-500/60" />
          <div className="w-3 h-3 rounded-full bg-yellow-500/60" />
          <div className="w-3 h-3 rounded-full bg-green-500/60" />
        </div>
        <span className="text-xs font-mono ml-2" style={{ color: textSecondary }}>preview.app</span>
      </div>
      <div className="p-6 space-y-4">
        <h3 className="text-lg font-bold" style={{ color: textPrimary }}>Dashboard</h3>
        <div className="grid grid-cols-2 gap-3">
          <div className="rounded-lg p-4" style={{ backgroundColor: surface, border: `1px solid ${border}` }}>
            <p className="text-xs mb-1" style={{ color: textSecondary }}>Revenue</p>
            <p className="text-xl font-bold" style={{ color: primary }}>$42,389</p>
          </div>
          <div className="rounded-lg p-4" style={{ backgroundColor: surface, border: `1px solid ${border}` }}>
            <p className="text-xs mb-1" style={{ color: textSecondary }}>Growth</p>
            <p className="text-xl font-bold" style={{ color: success }}>+23.5%</p>
          </div>
        </div>
        <div className="flex gap-3">
          <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{ backgroundColor: primary, color: textColorFor(primary) }}>Primary Action</button>
          <button className="px-4 py-2 rounded-lg text-sm font-medium" style={{ backgroundColor: secondary, color: textColorFor(secondary) }}>Secondary</button>
        </div>
        <p className="text-xs" style={{ color: textSecondary }}>This preview uses all 10 colors from your generated system.</p>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Main page                                                           */
/* ------------------------------------------------------------------ */

export default function PaletteForge() {
  const [prompt, setPrompt] = useState('');
  const [palette, setPalette] = useState<ColorSystem | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState<'swatches' | 'preview' | 'code'>('swatches');

  const generate = useCallback(async () => {
    if (prompt.trim().length < 5) {
      setError('Give me a bit more to work with — at least 5 characters.');
      return;
    }
    setError('');
    setLoading(true);
    setPalette(null);
    try {
      const res = await fetch('/api/demos/palette-forge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt: prompt.trim() }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || 'Generation failed.');
      }
      const data: ColorSystem = await res.json();
      setPalette(data);
      setActiveTab('swatches');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong.');
    } finally {
      setLoading(false);
    }
  }, [prompt]);

  const cssOutput = useMemo(() => {
    if (!palette) return '';
    return `:root {
${palette.colors.map((c) => `  --color-${c.name.toLowerCase().replace(/\s+/g, '-')}: ${c.hex};`).join('\n')}
}`;
  }, [palette]);

  const twOutput = useMemo(() => {
    if (!palette) return '';
    return `// tailwind.config.ts → theme.extend.colors
colors: {
${palette.colors.map((c) => `  '${c.name.toLowerCase().replace(/\s+/g, '-')}': '${c.hex}',`).join('\n')}
}`;
  }, [palette]);

  return (
    <div className="min-h-screen bg-[#0C1222] text-slate-200">
      {/* Header */}
      <div className="border-b border-slate-800">
        <div className="max-w-5xl mx-auto px-4 py-4 flex items-center gap-3">
          <Link href="/demos" className="text-slate-400 hover:text-white transition-colors">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <Palette className="w-6 h-6 text-orange-400" />
          <div>
            <h1 className="text-lg font-bold text-white">PaletteForge</h1>
            <p className="text-xs text-slate-400">AI Color System Generator</p>
          </div>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 py-8 space-y-8">
        {/* Input */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-slate-800/30 border border-slate-700/50 rounded-xl p-6 space-y-5"
        >
          <div>
            <label className="block text-sm font-medium text-slate-300 mb-2">Describe the mood, brand, or vibe</label>
            <div className="flex gap-3">
              <input
                type="text"
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && !loading && generate()}
                placeholder="e.g., Moody jazz lounge with velvet textures..."
                className="flex-1 bg-slate-900/60 border border-slate-700 rounded-lg px-4 py-3 text-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-orange-500/40 focus:border-orange-500/60"
              />
              <button
                onClick={generate}
                disabled={loading}
                className="px-6 py-3 bg-orange-600 hover:bg-orange-500 disabled:bg-slate-700 disabled:text-slate-400 text-white font-semibold rounded-lg transition-colors flex items-center gap-2 shrink-0"
              >
                {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
                {loading ? 'Forging...' : 'Forge'}
              </button>
            </div>
          </div>

          {/* Suggestions */}
          <div className="flex flex-wrap gap-2">
            {SUGGESTIONS.map((s) => (
              <button
                key={s}
                onClick={() => { setPrompt(s); setPalette(null); setError(''); }}
                className="text-xs px-3 py-1.5 rounded-full border border-slate-600 text-slate-300 hover:border-orange-500/50 hover:text-orange-300 transition-colors"
              >
                {s}
              </button>
            ))}
          </div>

          {error && (
            <div className="flex items-center gap-2 text-red-400 text-sm">
              <XCircle className="w-4 h-4 shrink-0" />
              {error}
            </div>
          )}
        </motion.div>

        {/* Results */}
        <AnimatePresence mode="wait">
          {palette && (
            <motion.div
              initial={{ opacity: 0, y: 30 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              className="space-y-6"
            >
              {/* Title */}
              <div className="text-center">
                <h2 className="text-2xl font-bold text-white">{palette.brandName}</h2>
                <p className="text-sm text-slate-400 mt-1">{palette.description}</p>
              </div>

              {/* Tabs */}
              <div className="flex gap-1 bg-slate-800/50 rounded-lg p-1 w-fit mx-auto">
                {[
                  { key: 'swatches' as const, label: 'Swatches', icon: Paintbrush },
                  { key: 'preview' as const, label: 'Live Preview', icon: Eye },
                  { key: 'code' as const, label: 'Code Export', icon: Code2 },
                ].map((tab) => (
                  <button
                    key={tab.key}
                    onClick={() => setActiveTab(tab.key)}
                    className={`flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-colors ${
                      activeTab === tab.key
                        ? 'bg-orange-600 text-white'
                        : 'text-slate-400 hover:text-white'
                    }`}
                  >
                    <tab.icon className="w-4 h-4" />
                    {tab.label}
                  </button>
                ))}
              </div>

              {/* Tab content */}
              {activeTab === 'swatches' && (
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-5 gap-3">
                  {palette.colors.map((c, i) => (
                    <SwatchCard key={c.name} color={c} index={i} />
                  ))}
                </div>
              )}

              {activeTab === 'preview' && <PreviewPanel colors={palette.colors} />}

              {activeTab === 'code' && (
                <div className="space-y-4">
                  <CodeBlock title="CSS Custom Properties" code={cssOutput} lang="css" />
                  <CodeBlock title="Tailwind Config" code={twOutput} lang="typescript" />
                </div>
              )}

              {/* Contrast pairs */}
              {palette.contrastPairs && palette.contrastPairs.length > 0 && (
                <div className="border border-slate-700/50 rounded-lg overflow-hidden">
                  <div className="px-4 py-3 bg-slate-800/60 border-b border-slate-700/50">
                    <span className="text-sm font-medium text-white">WCAG Contrast Pairs</span>
                  </div>
                  <div className="p-4 space-y-2">
                    {palette.contrastPairs.map((pair, i) => (
                      <div key={i} className="flex items-center gap-3 text-sm">
                        <span className="text-slate-300 font-mono text-xs min-w-[180px]">
                          {pair.foreground} / {pair.background}
                        </span>
                        <span className="text-slate-400 font-mono text-xs">{pair.ratio}</span>
                        <span className="flex items-center gap-1">
                          {pair.wcagAA
                            ? <CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
                            : <XCircle className="w-3.5 h-3.5 text-red-400" />}
                          <span className="text-xs text-slate-500">AA</span>
                        </span>
                        <span className="flex items-center gap-1">
                          {pair.wcagAAA
                            ? <CheckCircle2 className="w-3.5 h-3.5 text-green-400" />
                            : <XCircle className="w-3.5 h-3.5 text-red-400" />}
                          <span className="text-xs text-slate-500">AAA</span>
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Footer */}
        <div className="text-center text-xs text-slate-600 pt-8 pb-4">
          Built by The Hearth · AI-powered color system design
        </div>
      </div>
    </div>
  );
}
