'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, Send, Mic, Loader2, ShieldCheck } from 'lucide-react';
import Mascot from '../Mascot';
import DemoBadge from '../DemoBadge';
import { speak } from '@/lib/tts';
import { createStt, isSttSupported, type SttController } from '@/lib/stt';

interface Msg {
  role: 'child' | 'ai';
  content: string;
}

const GREETING = 'হ্যালো বন্ধু! 🌟 আমি তারা। আজ কী শিখতে চাও? আমাকে যা খুশি জিজ্ঞেস করো!';
const SUGGESTIONS = ['একটা মজার তথ্য বলো', 'সূর্য কেন গরম?', 'তোমার নাম কি?', 'গণিত শেখাও'];

export default function AiBuddy() {
  const router = useRouter();
  const [messages, setMessages] = useState<Msg[]>([{ role: 'ai', content: GREETING }]);
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const [listening, setListening] = useState(false);
  const [sttOk, setSttOk] = useState(false);
  const sttRef = useRef<SttController | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setSttOk(isSttSupported());
  }, []);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
  }, [messages, busy]);

  async function send(text: string) {
    const message = text.trim();
    if (!message || busy) return;
    setInput('');
    const history = messages.slice(-6);
    setMessages((m) => [...m, { role: 'child', content: message }]);
    setBusy(true);
    try {
      const res = await fetch('/api/ai/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message, history }),
      });
      const data = await res.json();
      const reply = data.ok ? data.reply : data.error ?? 'দুঃখিত, আবার চেষ্টা করো।';
      setMessages((m) => [...m, { role: 'ai', content: reply }]);
      speak(reply);
    } catch {
      setMessages((m) => [...m, { role: 'ai', content: 'নেটওয়ার্ক সমস্যা, আবার চেষ্টা করো।' }]);
    } finally {
      setBusy(false);
    }
  }

  function toggleMic() {
    if (!sttOk) return;
    if (listening) {
      sttRef.current?.stop();
      setListening(false);
      return;
    }
    const ctrl = createStt({
      onResult: (t) => {
        setInput(t);
        send(t);
      },
      onEnd: () => setListening(false),
      onError: () => setListening(false),
    });
    if (ctrl) {
      sttRef.current = ctrl;
      setListening(true);
      ctrl.start();
    }
  }

  return (
    <div className="flex min-h-dvh flex-col lg:pl-24">
      <header className="sticky top-0 z-30 bg-cream/90 px-4 pb-3 pt-4 backdrop-blur sm:px-6">
        <div className="mx-auto flex max-w-2xl items-center gap-3">
          <button
            onClick={() => router.push('/app/ai')}
            aria-label="ফিরে যাও"
            className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <Mascot mood="happy" size={40} />
          <div>
            <h1 className="font-heading text-lg font-extrabold text-ink">তারা</h1>
            <p className="text-[11px] text-ink-faint">AI বন্ধু · মানুষ নয়</p>
          </div>
          <DemoBadge className="ml-auto" />
        </div>
      </header>

      {/* messages */}
      <div ref={scrollRef} className="mx-auto w-full max-w-2xl flex-1 space-y-3 overflow-y-auto px-4 py-4 sm:px-6">
        <AnimatePresence initial={false}>
          {messages.map((m, i) => (
            <motion.div
              key={i}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              className={`flex items-end gap-2 ${m.role === 'child' ? 'justify-end' : 'justify-start'}`}
            >
              {m.role === 'ai' && <Mascot mood="idle" size={32} className="shrink-0" />}
              <div
                className={`max-w-[78%] rounded-3xl px-4 py-2.5 text-[15px] leading-relaxed shadow-card ${
                  m.role === 'child'
                    ? 'rounded-br-lg bg-mango-500 text-white'
                    : 'rounded-bl-lg bg-white text-ink'
                }`}
              >
                {m.content}
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
        {busy && (
          <div className="flex items-center gap-2">
            <Mascot mood="idle" size={32} />
            <div className="flex gap-1 rounded-3xl rounded-bl-lg bg-white px-4 py-3 shadow-card">
              {[0, 1, 2].map((d) => (
                <motion.span
                  key={d}
                  className="h-2 w-2 rounded-full bg-ink-faint"
                  animate={{ opacity: [0.3, 1, 0.3] }}
                  transition={{ duration: 1, repeat: Infinity, delay: d * 0.2 }}
                />
              ))}
            </div>
          </div>
        )}

        {messages.length <= 1 && (
          <div className="flex flex-wrap gap-2 pt-2">
            {SUGGESTIONS.map((s) => (
              <button
                key={s}
                onClick={() => send(s)}
                className="rounded-full bg-white px-3 py-1.5 text-sm font-semibold text-ink-soft shadow-card transition active:scale-95"
              >
                {s}
              </button>
            ))}
          </div>
        )}
      </div>

      {/* input */}
      <div className="sticky bottom-0 border-t border-cream-200 bg-cream/95 px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] backdrop-blur sm:px-6">
        <form
          onSubmit={(e) => {
            e.preventDefault();
            send(input);
          }}
          className="mx-auto flex max-w-2xl items-center gap-2"
        >
          {sttOk && (
            <button
              type="button"
              onClick={toggleMic}
              aria-label="কথা বলো"
              className={`flex h-11 w-11 shrink-0 items-center justify-center rounded-full transition active:scale-90 ${
                listening ? 'animate-pulse bg-mango-500 text-white' : 'bg-white text-mango-600 shadow-card'
              }`}
            >
              <Mic className="h-5 w-5" />
            </button>
          )}
          <input
            value={input}
            onChange={(e) => setInput(e.target.value.slice(0, 500))}
            placeholder={listening ? 'শুনছি…' : 'তারাকে কিছু জিজ্ঞেস করো…'}
            className="min-w-0 flex-1 rounded-full border-2 border-cream-200 bg-white px-4 py-2.5 text-[15px] text-ink outline-none transition focus:border-mango-500"
          />
          <button
            type="submit"
            disabled={busy || !input.trim()}
            aria-label="পাঠাও"
            className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-mango-500 text-white shadow-pop transition active:scale-90 disabled:opacity-50"
          >
            {busy ? <Loader2 className="h-5 w-5 animate-spin" /> : <Send className="h-5 w-5" />}
          </button>
        </form>
        <p className="mx-auto mt-1.5 flex max-w-2xl items-center justify-center gap-1 text-[11px] text-ink-faint">
          <ShieldCheck className="h-3.5 w-3.5 text-leaf-500" />
          তারা একটা AI বন্ধু, তত্ত্বাবধানে নিরাপদ
        </p>
      </div>
    </div>
  );
}
