"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Save, Users, Sparkles, ChevronDown, ChevronUp, Loader2 } from "lucide-react";

const COLORS = ["#6366f1","#8b5cf6","#ec4899","#ef4444","#f97316","#eab308","#22c55e","#14b8a6","#0ea5e9","#64748b"];

const inputCls = "w-full bg-white/[0.04] border border-white/[0.1] rounded-xl px-4 py-3 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500/50 transition-all";
const labelCls = "block text-xs font-semibold text-slate-400 mb-2 uppercase tracking-wide";
const cardCls = "bg-white/[0.03] border border-white/[0.07] rounded-2xl p-6";

export default function ConfigurePage() {
  const { botId } = useParams<{ botId: string }>();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState("");

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [systemPrompt, setSystemPrompt] = useState("");
  const [welcomeMessage, setWelcomeMessage] = useState("");
  const [botDisplayName, setBotDisplayName] = useState("");
  const [primaryColor, setPrimaryColor] = useState("#6366f1");
  const [temperature, setTemperature] = useState(0.7);
  const [leadCaptureEnabled, setLeadCaptureEnabled] = useState(false);
  const [leadCaptureTitle, setLeadCaptureTitle] = useState("Inainte sa incepem...");
  const [leadCaptureFields, setLeadCaptureFields] = useState("name,email");

  // AI generator state
  const [aiOpen, setAiOpen] = useState(false);
  const [aiBizType, setAiBizType] = useState("");
  const [aiDesc, setAiDesc] = useState("");
  const [aiTone, setAiTone] = useState("friendly");
  const [aiLoading, setAiLoading] = useState(false);
  const [aiError, setAiError] = useState("");

  useEffect(() => {
    fetch(`/api/bots/${botId}`).then(r => r.json()).then(bot => {
      setName(bot.name ?? "");
      setDescription(bot.description ?? "");
      setSystemPrompt(bot.config?.systemPrompt ?? "");
      setWelcomeMessage(bot.config?.welcomeMessage ?? "");
      setBotDisplayName(bot.config?.botDisplayName ?? "");
      setPrimaryColor(bot.config?.primaryColor ?? "#6366f1");
      setTemperature(bot.config?.temperature ?? 0.7);
      setLeadCaptureEnabled(bot.config?.leadCaptureEnabled ?? false);
      setLeadCaptureTitle(bot.config?.leadCaptureTitle ?? "Inainte sa incepem...");
      setLeadCaptureFields(bot.config?.leadCaptureFields ?? "name,email");
      setLoading(false);
    });
  }, [botId]);

  async function handleGeneratePrompt() {
    setAiLoading(true); setAiError("");
    const res = await fetch("/api/ai/generate-prompt", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ businessType: aiBizType, description: aiDesc, tone: aiTone }),
    });
    const data = await res.json();
    setAiLoading(false);
    if (!res.ok) { setAiError(data.error ?? "Eroare la generare."); return; }
    setSystemPrompt(data.prompt);
    setAiOpen(false);
  }

  async function handleSave() {
    setSaving(true); setError("");
    const res = await fetch(`/api/bots/${botId}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, description, config: { systemPrompt, welcomeMessage, botDisplayName, primaryColor, temperature, leadCaptureEnabled, leadCaptureTitle, leadCaptureFields } }),
    });
    setSaving(false);
    if (!res.ok) { const d = await res.json(); setError(d.error ?? "Eroare la salvare."); }
    else { setSaved(true); setTimeout(() => setSaved(false), 2500); }
  }

  if (loading) return (
    <div className="p-8 flex items-center justify-center h-full">
      <div className="text-slate-500 text-sm">Se incarca...</div>
    </div>
  );

  return (
    <div className="p-8 max-w-3xl mx-auto">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-bold text-white">Configurare chatbot</h1>
          <p className="text-slate-500 mt-1 text-sm">{name}</p>
        </div>
        <button onClick={handleSave} disabled={saving}
          className="flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 text-white px-5 py-2.5 rounded-xl text-sm font-bold transition-all shadow-lg shadow-indigo-500/20 disabled:opacity-50">
          <Save className="w-4 h-4" />
          {saving ? "Se salveaza..." : saved ? "✓ Salvat!" : "Salveaza"}
        </button>
      </div>

      {error && <div className="bg-red-500/10 border border-red-500/20 text-red-400 text-sm rounded-xl px-4 py-3 mb-6">{error}</div>}

      <div className="space-y-5">
        {/* General */}
        <div className={cardCls}>
          <h2 className="font-semibold text-white mb-4 text-sm uppercase tracking-wide">Informatii generale</h2>
          <div className="space-y-4">
            <div>
              <label className={labelCls}>Nume intern</label>
              <input value={name} onChange={e => setName(e.target.value)} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>Descriere</label>
              <input value={description} onChange={e => setDescription(e.target.value)} className={inputCls} placeholder="Scurta descriere..." />
            </div>
          </div>
        </div>

        {/* Personality */}
        <div className={cardCls}>
          <div className="flex items-center justify-between mb-1">
            <h2 className="font-semibold text-white text-sm uppercase tracking-wide">Personalitate</h2>
            <button onClick={() => setAiOpen(!aiOpen)}
              className="flex items-center gap-1.5 text-xs font-semibold text-indigo-400 hover:text-indigo-300 bg-indigo-500/10 hover:bg-indigo-500/20 border border-indigo-500/20 px-3 py-1.5 rounded-lg transition-all">
              <Sparkles className="w-3.5 h-3.5" />
              Genereaza cu AI
              {aiOpen ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
            </button>
          </div>
          <p className="text-xs text-slate-500 mb-4">Acesta este „creierul" chatbotului. Cu cat e mai detaliat, cu atat mai bun.</p>

          {/* AI Generator Panel */}
          {aiOpen && (
            <div className="bg-indigo-500/5 border border-indigo-500/20 rounded-xl p-4 mb-4 space-y-3">
              <p className="text-xs font-semibold text-indigo-300">✨ Descrie afacerea ta — AI genereaza System Prompt-ul perfect</p>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-slate-500 mb-1.5">Tip afacere</label>
                  <input value={aiBizType} onChange={e => setAiBizType(e.target.value)}
                    placeholder="ex: Restaurant, Salon, Clinica..."
                    className="w-full bg-white/[0.05] border border-white/[0.1] rounded-lg px-3 py-2 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-indigo-500/50" />
                </div>
                <div>
                  <label className="block text-xs text-slate-500 mb-1.5">Ton dorit</label>
                  <select value={aiTone} onChange={e => setAiTone(e.target.value)}
                    className="w-full bg-white/[0.05] border border-white/[0.1] rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:ring-1 focus:ring-indigo-500/50">
                    <option value="friendly">Prietenos</option>
                    <option value="formal">Formal/Profesional</option>
                    <option value="casual">Casual/Relaxat</option>
                    <option value="sales">Orientat vanzari</option>
                  </select>
                </div>
              </div>
              <div>
                <label className="block text-xs text-slate-500 mb-1.5">Descrie afacerea ta *</label>
                <textarea value={aiDesc} onChange={e => setAiDesc(e.target.value)} rows={3}
                  placeholder="ex: Avem un restaurant romanesc in Cluj, servim mancare traditionala, program luni-duminica 12-23, facem rezervari si livrari in zona Centru..."
                  className="w-full bg-white/[0.05] border border-white/[0.1] rounded-lg px-3 py-2 text-sm text-white placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-indigo-500/50 resize-none" />
              </div>
              {aiError && <p className="text-xs text-red-400">{aiError}</p>}
              <button onClick={handleGeneratePrompt} disabled={aiLoading || !aiDesc.trim()}
                className="flex items-center gap-2 bg-gradient-to-r from-indigo-600 to-violet-600 hover:from-indigo-500 hover:to-violet-500 disabled:opacity-50 text-white px-4 py-2 rounded-lg text-sm font-semibold transition-all">
                {aiLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
                {aiLoading ? "Se genereaza..." : "Genereaza System Prompt"}
              </button>
            </div>
          )}

          <div className="space-y-4">
            <div>
              <label className={labelCls}>Instructiuni principale (System Prompt)</label>
              <textarea value={systemPrompt} onChange={e => setSystemPrompt(e.target.value)} rows={10}
                className={`${inputCls} resize-y font-mono`}
                placeholder="Esti [Nume], asistentul de la [Firma]. Ajuti clientii cu... Tonul tau este..." />
              <p className="text-xs text-slate-600 mt-1.5">💡 Include: firma, produse/servicii, ton dorit, ce NU trebuie sa faca</p>
            </div>
            <div>
              <label className={labelCls}>Mesaj de bun venit</label>
              <input value={welcomeMessage} onChange={e => setWelcomeMessage(e.target.value)} className={inputCls} />
            </div>
            <div>
              <label className={labelCls}>
                Creativitate raspunsuri — <span className="text-indigo-400">{temperature < 0.3 ? "Precis (FAQ)" : temperature < 0.7 ? "Echilibrat" : "Creativ (vanzari)"}</span>
              </label>
              <input type="range" min={0} max={1} step={0.1} value={temperature}
                onChange={e => setTemperature(parseFloat(e.target.value))}
                className="w-full accent-indigo-500" />
              <div className="flex justify-between text-xs text-slate-600 mt-1">
                <span>Mai precis</span><span>Mai creativ</span>
              </div>
            </div>
          </div>
        </div>

        {/* Lead Capture */}
        <div className={cardCls}>
          <div className="flex items-center justify-between mb-4">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 bg-purple-500/10 border border-purple-500/20 rounded-xl flex items-center justify-center">
                <Users className="w-4 h-4 text-purple-400" />
              </div>
              <div>
                <h2 className="font-semibold text-white text-sm">Captare leaduri</h2>
                <p className="text-xs text-slate-500">Colecteaza date de contact inainte de conversatie</p>
              </div>
            </div>
            <button onClick={() => setLeadCaptureEnabled(!leadCaptureEnabled)}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${leadCaptureEnabled ? "bg-indigo-600" : "bg-white/10"}`}>
              <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${leadCaptureEnabled ? "translate-x-6" : "translate-x-1"}`} />
            </button>
          </div>
          {leadCaptureEnabled && (
            <div className="space-y-4 pt-4 border-t border-white/[0.06]">
              <div>
                <label className={labelCls}>Titlu formular</label>
                <input value={leadCaptureTitle} onChange={e => setLeadCaptureTitle(e.target.value)} className={inputCls} placeholder="Inainte sa incepem..." />
              </div>
              <div>
                <label className={labelCls}>Campuri colectate</label>
                <div className="flex flex-wrap gap-2">
                  {["name", "email", "phone"].map(field => {
                    const active = leadCaptureFields.split(",").map(f => f.trim()).includes(field);
                    const labels: Record<string, string> = { name: "Nume", email: "Email", phone: "Telefon" };
                    return (
                      <button key={field} onClick={() => {
                        const current = leadCaptureFields.split(",").map(f => f.trim()).filter(Boolean);
                        const next = active ? current.filter(f => f !== field) : [...current, field];
                        setLeadCaptureFields(next.join(","));
                      }} className={`px-4 py-2 rounded-xl text-sm font-semibold transition-all ${active ? "bg-indigo-600 text-white shadow-lg shadow-indigo-500/20" : "bg-white/[0.05] text-slate-400 hover:bg-white/[0.08] border border-white/[0.08]"}`}>
                        {labels[field]}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Appearance */}
        <div className={cardCls}>
          <h2 className="font-semibold text-white mb-4 text-sm uppercase tracking-wide">Aspect widget</h2>
          <div className="space-y-5">
            <div>
              <label className={labelCls}>Numele afisat clientilor</label>
              <input value={botDisplayName} onChange={e => setBotDisplayName(e.target.value)} className={inputCls} placeholder="Asistent" />
            </div>
            <div>
              <label className={labelCls}>Culoarea principala</label>
              <div className="flex flex-wrap gap-2.5 mt-1">
                {COLORS.map(c => (
                  <button key={c} onClick={() => setPrimaryColor(c)}
                    className={`w-9 h-9 rounded-full transition-all hover:scale-110 ${primaryColor === c ? "ring-2 ring-offset-2 ring-offset-[#0d1117] ring-white scale-110" : ""}`}
                    style={{ backgroundColor: c }} />
                ))}
              </div>
            </div>

            {/* Preview */}
            <div>
              <label className={labelCls}>Previzualizare</label>
              <div className="relative bg-[#080c14] border border-white/[0.06] rounded-2xl overflow-hidden h-48">
                <div className="absolute bottom-4 right-4 flex flex-col items-end gap-2">
                  <div className="bg-white/[0.08] backdrop-blur-sm border border-white/[0.1] rounded-2xl rounded-br-sm px-4 py-2.5 text-white text-sm shadow-xl max-w-52">
                    {welcomeMessage || "Buna ziua! Cu ce va pot ajuta?"}
                  </div>
                  <div className="w-12 h-12 rounded-full flex items-center justify-center text-white shadow-xl text-xl" style={{ backgroundColor: primaryColor }}>
                    🤖
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
