import { useState, useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { Save, Loader2, CheckCircle, Users, RefreshCw, UserCog } from 'lucide-react';
import { characters } from '../api/client';

interface ToneOfVoice {
  formality: string;
  emoji_frequency: string;
  message_length: string;
  humor_level: string;
  flirtation_level: string;
}

interface SalesBehavior {
  min_messages_before_pitch: number;
  cooldown_minutes: number;
  pitch_style: string;
}

interface ConversationProfile {
  characterId: string;
  style: string;
  toneOfVoice: ToneOfVoice;
  languagePatterns: { common_phrases: string[]; filler_words: string[] };
  salesBehavior: SalesBehavior;
}

interface CharacterOption { id: string; name: string; }

const FORMALITY_OPTIONS = [
  { value: 'formal', label: 'Resmi', desc: 'Kibar ve profesyonel' },
  { value: 'casual', label: 'Rahat', desc: 'Arkadaş gibi, samimi' },
  { value: 'flirty', label: 'Flörtöz', desc: 'İlgili ve çekici' },
  { value: 'playful', label: 'Oyuncu', desc: 'Eğlenceli ve enerjik' },
];

const EMOJI_OPTIONS = [
  { value: 'none', label: 'Yok' },
  { value: 'low', label: 'Az' },
  { value: 'medium', label: 'Orta' },
  { value: 'high', label: 'Çok' },
];

const LENGTH_OPTIONS = [
  { value: 'short', label: 'Kısa', desc: '1-2 cümle' },
  { value: 'medium', label: 'Orta', desc: '2-4 cümle' },
  { value: 'long', label: 'Uzun', desc: '4+ cümle' },
];

const HUMOR_OPTIONS = [
  { value: 'none', label: 'Yok' },
  { value: 'occasional', label: 'Ara sıra' },
  { value: 'frequent', label: 'Sık' },
];

const FLIRT_OPTIONS = [
  { value: 'none', label: 'Yok' },
  { value: 'subtle', label: 'Hafif' },
  { value: 'moderate', label: 'Orta' },
  { value: 'bold', label: 'Cesur' },
];

const PITCH_OPTIONS = [
  { value: 'subtle', label: 'Yumuşak', desc: 'Doğal geçiş' },
  { value: 'moderate', label: 'Orta', desc: 'Belirgin ama nazik' },
  { value: 'direct', label: 'Direkt', desc: 'Açık teklif' },
];

const STYLE_OPTIONS = [
  { value: 'neseli', label: 'Neşeli' },
  { value: 'romantik', label: 'Romantik' },
  { value: 'gizemli', label: 'Gizemli' },
  { value: 'enerjik', label: 'Enerjik' },
  { value: 'sakin', label: 'Sakin' },
];

export default function SettingsPersona() {
  const [charList, setCharList] = useState<CharacterOption[]>([]);
  const [selectedChar, setSelectedChar] = useState('');
  const [profile, setProfile] = useState<ConversationProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [loadingChars, setLoadingChars] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const { data } = await characters.list();
        const list = (data?.data ?? data ?? []).map((c: any) => ({
          id: c.id,
          name: c.identity?.name ?? c.id.slice(0, 8),
        }));
        setCharList(list);
        if (list.length > 0 && !selectedChar) setSelectedChar(list[0].id);
      } catch {}
      setLoadingChars(false);
    })();
  }, []);

  const loadProfile = useCallback(async () => {
    if (!selectedChar) return;
    setLoading(true);
    try {
      const { data } = await characters.getConversationProfile(selectedChar);
      const p = data?.data ?? data;
      setProfile({
        characterId: selectedChar,
        style: p?.style ?? 'neseli',
        toneOfVoice: {
          formality: p?.toneOfVoice?.formality ?? 'casual',
          emoji_frequency: p?.toneOfVoice?.emoji_frequency ?? 'medium',
          message_length: p?.toneOfVoice?.message_length ?? 'medium',
          humor_level: p?.toneOfVoice?.humor_level ?? 'occasional',
          flirtation_level: p?.toneOfVoice?.flirtation_level ?? 'subtle',
        },
        languagePatterns: {
          common_phrases: p?.languagePatterns?.common_phrases ?? [],
          filler_words: p?.languagePatterns?.filler_words ?? [],
        },
        salesBehavior: {
          min_messages_before_pitch: p?.salesBehavior?.min_messages_before_pitch ?? 10,
          cooldown_minutes: p?.salesBehavior?.cooldown_minutes ?? 60,
          pitch_style: p?.salesBehavior?.pitch_style ?? 'subtle',
        },
      });
    } catch {
      setProfile({
        characterId: selectedChar, style: 'neseli',
        toneOfVoice: { formality: 'casual', emoji_frequency: 'medium', message_length: 'medium', humor_level: 'occasional', flirtation_level: 'subtle' },
        languagePatterns: { common_phrases: [], filler_words: [] },
        salesBehavior: { min_messages_before_pitch: 10, cooldown_minutes: 60, pitch_style: 'subtle' },
      });
    }
    setLoading(false);
  }, [selectedChar]);

  useEffect(() => { loadProfile(); }, [loadProfile]);

  async function saveProfile() {
    if (!profile || !selectedChar) return;
    setSaving(true);
    try {
      await characters.updateConversationProfile(selectedChar, profile as unknown as Record<string, unknown>);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch { /* save failed — UI state is enough */ }
    setSaving(false);
  }

  function updateTone(key: keyof ToneOfVoice, value: string) {
    if (!profile) return;
    setProfile({ ...profile, toneOfVoice: { ...profile.toneOfVoice, [key]: value } });
  }

  function updateSales(key: keyof SalesBehavior, value: string | number) {
    if (!profile) return;
    setProfile({ ...profile, salesBehavior: { ...profile.salesBehavior, [key]: value } });
  }

  if (loadingChars) return (
    <div className="flex min-h-[40vh] items-center justify-center">
      <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
    </div>
  );

  return (
    <div className="max-w-2xl">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center gap-3 mb-2">
          <div className="w-10 h-10 rounded-xl bg-violet-500/10 flex items-center justify-center">
            <UserCog className="w-5 h-5 text-violet-400" />
          </div>
          <div>
            <h1 className="text-xl font-bold text-white">Konuşma Tarzı</h1>
            <p className="text-[13px] text-slate-500">Karakterinizin sohbet kişiliğini ve satış davranışını ayarlayın.</p>
          </div>
        </div>
      </div>

      {/* Character selector */}
      <div className="mb-6 p-5 rounded-2xl bg-white/[0.02] border border-white/[0.06]">
        <div className="flex items-center gap-2 mb-3">
          <Users className="w-4 h-4 text-indigo-400" />
          <span className="text-[13px] font-semibold text-white">Karakter Seçin</span>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={selectedChar}
            onChange={(e) => setSelectedChar(e.target.value)}
            className="flex-1 px-4 py-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all appearance-none cursor-pointer"
          >
            {charList.map((c) => (
              <option key={c.id} value={c.id} className="bg-[#12121a] text-slate-300">{c.name}</option>
            ))}
          </select>
          <button
            onClick={loadProfile}
            className="p-3 rounded-xl bg-white/[0.03] border border-white/[0.08] text-slate-500 hover:text-slate-300 hover:bg-white/[0.06] transition-all cursor-pointer"
          >
            <RefreshCw className="w-4 h-4" />
          </button>
        </div>
      </div>

      {loading ? (
        <div className="flex min-h-[30vh] items-center justify-center">
          <div className="h-6 w-6 animate-spin rounded-full border-2 border-indigo-500 border-t-transparent" />
        </div>
      ) : profile ? (
        <div className="space-y-5">
          <Section title="Genel Stil" index={0}>
            <OptionRow options={STYLE_OPTIONS} value={profile.style} onChange={(v) => setProfile({ ...profile, style: v })} />
          </Section>

          <Section title="Konuşma Tonu" index={1}>
            <div className="grid grid-cols-2 gap-2">
              {FORMALITY_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => updateTone('formality', opt.value)}
                  className={`p-3.5 rounded-xl border text-left transition-all cursor-pointer ${
                    profile.toneOfVoice.formality === opt.value
                      ? 'border-indigo-500/50 bg-indigo-500/[0.08] text-white ring-1 ring-indigo-500/20'
                      : 'border-white/[0.06] bg-white/[0.02] text-slate-400 hover:border-white/[0.12]'
                  }`}
                >
                  <div className="text-[13px] font-medium">{opt.label}</div>
                  <div className="text-[11px] text-slate-500 mt-0.5">{opt.desc}</div>
                </button>
              ))}
            </div>
          </Section>

          <Section title="Emoji Kullanımı" index={2}>
            <OptionRow options={EMOJI_OPTIONS} value={profile.toneOfVoice.emoji_frequency} onChange={(v) => updateTone('emoji_frequency', v)} />
          </Section>

          <Section title="Mesaj Uzunluğu" index={3}>
            <div className="grid grid-cols-3 gap-2">
              {LENGTH_OPTIONS.map((opt) => (
                <button
                  key={opt.value}
                  onClick={() => updateTone('message_length', opt.value)}
                  className={`p-3.5 rounded-xl border text-center transition-all cursor-pointer ${
                    profile.toneOfVoice.message_length === opt.value
                      ? 'border-indigo-500/50 bg-indigo-500/[0.08] text-white ring-1 ring-indigo-500/20'
                      : 'border-white/[0.06] bg-white/[0.02] text-slate-400 hover:border-white/[0.12]'
                  }`}
                >
                  <div className="text-[13px] font-medium">{opt.label}</div>
                  <div className="text-[11px] text-slate-500 mt-0.5">{opt.desc}</div>
                </button>
              ))}
            </div>
          </Section>

          <Section title="Mizah Seviyesi" index={4}>
            <OptionRow options={HUMOR_OPTIONS} value={profile.toneOfVoice.humor_level} onChange={(v) => updateTone('humor_level', v)} />
          </Section>

          <Section title="Flört Seviyesi" index={5}>
            <OptionRow options={FLIRT_OPTIONS} value={profile.toneOfVoice.flirtation_level} onChange={(v) => updateTone('flirtation_level', v)} />
          </Section>

          <Section title="Satış Davranışı" index={6}>
            <div className="space-y-4">
              <div>
                <label className="text-[12px] text-slate-500 mb-2 block font-medium">Satış öncesi minimum mesaj sayısı</label>
                <input
                  type="number" min={1} max={100}
                  value={profile.salesBehavior.min_messages_before_pitch}
                  onChange={(e) => updateSales('min_messages_before_pitch', parseInt(e.target.value) || 10)}
                  className="w-28 px-4 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all"
                />
              </div>
              <div>
                <label className="text-[12px] text-slate-500 mb-2 block font-medium">Satışlar arası bekleme (dakika)</label>
                <input
                  type="number" min={5} max={1440}
                  value={profile.salesBehavior.cooldown_minutes}
                  onChange={(e) => updateSales('cooldown_minutes', parseInt(e.target.value) || 60)}
                  className="w-28 px-4 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.08] text-sm text-slate-300 focus:outline-none focus:border-indigo-500/50 focus:ring-2 focus:ring-indigo-500/10 transition-all"
                />
              </div>
              <div>
                <label className="text-[12px] text-slate-500 mb-2 block font-medium">Satış tarzı</label>
                <div className="grid grid-cols-3 gap-2">
                  {PITCH_OPTIONS.map((opt) => (
                    <button
                      key={opt.value}
                      onClick={() => updateSales('pitch_style', opt.value)}
                      className={`p-3.5 rounded-xl border text-center transition-all cursor-pointer ${
                        profile.salesBehavior.pitch_style === opt.value
                          ? 'border-indigo-500/50 bg-indigo-500/[0.08] text-white ring-1 ring-indigo-500/20'
                          : 'border-white/[0.06] bg-white/[0.02] text-slate-400 hover:border-white/[0.12]'
                      }`}
                    >
                      <div className="text-[13px] font-medium">{opt.label}</div>
                      <div className="text-[11px] text-slate-500 mt-0.5">{opt.desc}</div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </Section>

          {/* Save */}
          <div className="pt-2 flex items-center gap-3">
            <motion.button
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={saveProfile}
              disabled={saving}
              className="flex items-center gap-2 px-6 py-3 rounded-xl bg-gradient-to-r from-indigo-600 to-violet-600 text-sm font-semibold shadow-lg shadow-indigo-500/20 disabled:opacity-50 cursor-pointer"
            >
              {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
              Kaydet
            </motion.button>
            {saved && (
              <motion.span
                initial={{ opacity: 0, x: -10 }}
                animate={{ opacity: 1, x: 0 }}
                className="text-[12px] text-emerald-400 flex items-center gap-1"
              >
                <CheckCircle className="w-3.5 h-3.5" /> Başarıyla kaydedildi
              </motion.span>
            )}
          </div>
        </div>
      ) : (
        <div className="text-center py-16 text-slate-500 text-sm">Karakter seçiniz</div>
      )}
    </div>
  );
}

function Section({ title, children, index }: { title: string; children: React.ReactNode; index: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.06 }}
      className="p-5 rounded-2xl bg-white/[0.02] border border-white/[0.06]"
    >
      <h3 className="text-[14px] font-semibold text-white mb-3">{title}</h3>
      {children}
    </motion.div>
  );
}

function OptionRow({ options, value, onChange }: {
  options: { value: string; label: string }[];
  value: string;
  onChange: (v: string) => void;
}) {
  return (
    <div className="flex gap-2">
      {options.map((opt) => (
        <button
          key={opt.value}
          onClick={() => onChange(opt.value)}
          className={`flex-1 py-2.5 rounded-xl border text-[12px] font-medium transition-all cursor-pointer ${
            value === opt.value
              ? 'border-indigo-500/50 bg-indigo-500/[0.08] text-white ring-1 ring-indigo-500/20'
              : 'border-white/[0.06] bg-white/[0.02] text-slate-500 hover:border-white/[0.12] hover:text-slate-300'
          }`}
        >
          {opt.label}
        </button>
      ))}
    </div>
  );
}
