"use client";
import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { PaperPlaneIcon } from "@radix-ui/react-icons";
import { IoIosLink } from "react-icons/io";
import Image from "next/image";

export default function ChatBox() {
  type Message = {
    id: number;
    type: "user" | "bot" | "typing";
    text?: string;
    file?: string;
    fileName?: string;
    fileType?: "image" | "pdf";
    timestamp?: string;
  };

  const botQuestions = [
    "Hey there! 😊 Let's get to know you a bit.",
    "First up, what's your name?",
    "Nice to meet you! Which city are you messaging from?",
    "Cool! Mind sharing your phone number? 📱 Just numbers, please.",
    "Awesome. So, what kind of service are you looking for?",
    "Do you want to receive updates and offers via WhatsApp? (yes/no)",
    "Great! What's your email in case we need to send you a quick follow-up?",
    "Do you already have a budget in mind for your project?",
    "When would you like the project to be completed? Any specific timeline?",
    "How did you hear about us? (e.g., Google, friend, social media)",
    "And if you don’t mind, share a little more about your project idea. We'd love to hear it! 💡",
    "Perfect! 🎉 That’s all we need for now. Our team will get back to you soon!"
  ];

  const [messages, setMessages] = useState<Message[]>([{
    id: 1,
    text: botQuestions[0],
    type: "bot",
    timestamp: new Date().toLocaleTimeString()
  }, {
    id: 2,
    text: botQuestions[1],
    type: "bot",
    timestamp: new Date().toLocaleTimeString()
  }]);

  const [input, setInput] = useState("");
  const [showChat, setShowChat] = useState(false);
  const [step, setStep] = useState(1);
  const [userData, setUserData] = useState({
    name: "",
    city: "",
    number: "",
    service: "",
    whatsapp: "",
    email: "",
    budget: "",
    timeline: "",
    referral: "",
    description: ""
  });

  const chatEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleFileUpload = (file: File) => {
    const fileUrl = URL.createObjectURL(file);
    const type = file.type.startsWith("image/") ? "image" : "pdf";
    setMessages((prev) => [...prev, {
      id: Date.now(),
      file: fileUrl,
      fileName: file.name,
      fileType: type,
      type: "user",
      timestamp: new Date().toLocaleTimeString()
    }]);
  };

  const sendMessage = async () => {
    if (!input.trim()) return;

    const newUserMsg: Message = {
      id: Date.now(),
      text: input,
      type: "user",
      timestamp: new Date().toLocaleTimeString()
    };
    setMessages((prev) => [...prev, newUserMsg]);

    const fields = [
      "name", "city", "number", "service", "whatsapp",
      "email", "budget", "timeline", "referral", "description"
    ];
    if (step > 1 && step <= fields.length + 1) {
      setUserData((prev) => ({ ...prev, [fields[step - 2]]: input }));
    }

    setInput("");

    setMessages((prev) => [...prev, { id: Date.now() + 1, type: "typing" }]);

    setTimeout(async () => {
      setMessages((prev) => prev.filter((msg) => msg.type !== "typing").concat({
        id: Date.now() + 2,
        text: botQuestions[step + 1],
        type: "bot",
        timestamp: new Date().toLocaleTimeString()
      }));

      setStep((prev) => prev + 1);

      if (step === fields.length + 1) {
        try {
          const res = await fetch("/api/save-user-data", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(userData)
          });
          if (!res.ok) throw new Error("Failed to save data");
          console.log("User data saved 🎉");
        } catch (err) {
          console.error("Error saving data", err);
        }
      }
    }, 1000);
  };

  return (
    <>
      <button
        onClick={() => setShowChat(!showChat)}
        className="fixed bottom-4 right-4 z-50 bg-gradient-to-tr from-orange-400 to-red-500 text-white w-14 h-14 rounded-full shadow-2xl flex items-center justify-center hover:scale-105 transition-all"
      >
        {showChat ? "➖" : "💬"}
      </button>

      <AnimatePresence>
        {showChat && (
          <motion.div
            initial={{ opacity: 0, scale: 0.4, y: 40, x: 40 }}
            animate={{ opacity: 1, scale: 1, y: 0, x: 0 }}
            exit={{ opacity: 0, scale: 0.4, y: 40, x: 40 }}
            transition={{ duration: 0.35, ease: [0.2, 0.8, 0.2, 1] }}
            className="origin-bottom-right fixed bottom-20 right-14 w-[400px] max-h-[75vh] bg-white backdrop-blur-xl rounded-3xl shadow-2xl border border-gray-300 flex flex-col overflow-hidden z-40"
          >
            <div
              className="flex gap-3 text-white px-6 py-7"
              style={{ backgroundImage: "url('images/chatbotheaderbg.png')", backgroundBlendMode: "overlay", backgroundSize: "cover", backgroundPosition: "center" }}
            >
              <Image src="/images/chatbotrobot.svg" width={100} height={50} alt="Chat with Fruxinfo support" className="h-[40px] w-[40px]" />
              <div>
                <div className="text-xs text-[#FFF]">Chat With</div>
                <div className="md:text-[16px] font-bold text-[#E77025]">Fruxinfo Bot</div>
              </div>
            </div>

            <div className="flex-1 p-4 space-y-3 overflow-y-auto custom-scroll bg-white bg-cover bg-no-repeat">
              {messages.map((msg) => (
                <div
                  key={msg.id}
                  className={`max-w-[80%] px-4 py-2 rounded-2xl text-sm shadow ${msg.type === "bot" ? "bg-[#FFF7F2] border border-[#E77025] text-gray-800 self-start" : msg.type === "typing" ? "italic text-gray-400 self-start" : "bg-[#DEFCFF] text-[#616161] border border-[#25D4E7] self-end ml-auto"}`}
                >
                  {msg.type === "typing"
                    ? "typing..."
                    : msg.file
                    ? msg.fileType === "image"
                      ? <Image src={msg.file} alt="Uploaded" width={1200} height={600} className="max-w-full rounded-lg" />
                      : (<div><span className="block font-semibold">📄 PDF:</span><a href={msg.file} download={msg.fileName} className="text-blue-600 underline">{msg.fileName}</a></div>)
                    : msg.text}
                  {msg.timestamp && (<div className="text-[10px] text-gray-400 text-right mt-1">{msg.timestamp}</div>)}
                </div>
              ))}
              <div ref={chatEndRef} />
            </div>

            <div className="flex items-center gap-2 p-3 bg-white/60 backdrop-blur">
              <input id="fileUpload" type="file" className="hidden" accept="image/*,application/pdf" onChange={(e) => e.target.files?.[0] && handleFileUpload(e.target.files[0])} />
              <label htmlFor="fileUpload" className="cursor-pointer p-2 text-orange-500 bg-[#FAFAFA] hover:bg-orange-100 rounded-full transition shadow">
                <IoIosLink />
              </label>
              <input
                className="flex-1 bg-[#FAFAFA] border border-gray-300 rounded-full px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400"
                placeholder="Enter Your Message..."
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && sendMessage()}
              />
              <button
                onClick={sendMessage}
                className="p-2 text-white bg-orange-500 hover:bg-orange-600 rounded-full transition"
              >
                <PaperPlaneIcon className="h-4 w-4" />
              </button>
            </div>

            <div className="text-center text-xs text-gray-500 py-2 border-t border-gray-200 bg-white/70">
              Powered by <span className="font-semibold text-[#E77025]">Fruxinfo</span>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
