"use client";

import React, { useRef, useEffect, useState } from "react";
import { useApp } from "@/context/AppContext";
import { X, Send, RotateCcw, MessageSquare, Sparkles } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

export const AIAssistant: React.FC = () => {
  const { isAiOpen, setIsAiOpen, aiMessages, sendAiMessage, resetAiChat } = useApp();
  const [input, setInput] = useState("");
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const quickQuestions = [
    "What size do I need for my height?",
    "Tell me about your fabrics (GSM)",
    "Recommend a streetwear outfit",
    "How fast is shipping in Pakistan?"
  ];

  const handleSend = (e: React.FormEvent) => {
    e.preventDefault();
    if (input.trim()) {
      sendAiMessage(input);
      setInput("");
    }
  };

  const handleQuickQuestion = (q: string) => {
    sendAiMessage(q);
  };

  // Scroll to bottom on new message
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [aiMessages, isAiOpen]);

  return (
    <AnimatePresence>
      {isAiOpen && (
        <>
          {/* Overlay */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 0.5 }}
            exit={{ opacity: 0 }}
            onClick={() => setIsAiOpen(false)}
            className="fixed inset-0 z-40 bg-black backdrop-blur-sm"
          />

          {/* Drawer Panel */}
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "tween", duration: 0.35, ease: [0.16, 1, 0.3, 1] }}
            className="fixed top-0 right-0 z-50 flex h-full w-full flex-col bg-[#F8F7F2] border-l border-[#1A1A1A]/10 shadow-2xl sm:w-[450px]"
          >
            {/* Header */}
            <div className="flex h-20 items-center justify-between border-b border-[#1A1A1A]/10 px-6">
              <div className="flex items-center gap-2">
                <Sparkles className="h-4 w-4 text-[#D4AF37]" />
                <h3 className="font-serif text-sm font-bold tracking-widest text-black">STARBOY AI STYLIST</h3>
              </div>
              <div className="flex items-center gap-4">
                <button
                  onClick={resetAiChat}
                  title="Reset conversation"
                  className="text-neutral-500 hover:text-black transition-colors"
                >
                  <RotateCcw className="h-4 w-4" />
                </button>
                <button
                  onClick={() => setIsAiOpen(false)}
                  className="text-neutral-500 hover:text-black transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
            </div>

            {/* Chat Area */}
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
              {aiMessages.map((msg) => (
                <div
                  key={msg.id}
                  className={`flex ${msg.sender === "user" ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-[85%] border px-4 py-3 text-xs leading-relaxed ${
                      msg.sender === "user"
                        ? "bg-[#0A0A0A] border-[#0A0A0A] text-[#F8F7F2]"
                        : "bg-white border-[#1A1A1A]/10 text-[#1A1A1A]"
                    }`}
                  >
                    <p className="font-sans whitespace-pre-wrap">{msg.text}</p>
                  </div>
                </div>
              ))}
              <div ref={messagesEndRef} />
            </div>

            {/* Quick Suggestions & Input */}
            <div className="border-t border-[#1A1A1A]/10 p-6 bg-white space-y-4">
              
              {/* Quick Prompt Grid */}
              <div className="grid grid-cols-2 gap-2">
                {quickQuestions.map((q, idx) => (
                  <button
                    key={idx}
                    onClick={() => handleQuickQuestion(q)}
                    className="border border-[#1A1A1A]/10 hover:border-[#D4AF37] hover:bg-[#F8F7F2] p-2 text-left text-[10px] uppercase font-semibold tracking-wider text-neutral-600 hover:text-black transition-all"
                  >
                    {q}
                  </button>
                ))}
              </div>

              {/* Message Input Box */}
              <form onSubmit={handleSend} className="flex gap-2">
                <input
                  type="text"
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder="Ask about size, fabrics, cuts..."
                  className="flex-1 border border-[#1A1A1A]/10 bg-[#F8F7F2] px-4 py-2.5 text-xs outline-none focus:border-[#D4AF37] transition-colors"
                />
                <button
                  type="submit"
                  className="bg-[#0A0A0A] text-white hover:bg-[#D4AF37] hover:text-black p-3 transition-colors duration-200"
                >
                  <Send className="h-4 w-4" />
                </button>
              </form>

            </div>

          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};
