"use client";

import React, { useState, useRef, useEffect } from "react";
import { Send, X } from "lucide-react";
import { useSettings } from "@/context/SettingsContext";

export default function WhatsappChatModal({ isOpen, onClose }) {
  const { settings } = useSettings();
  const modalRef = useRef(null);

  const [name, setName] = useState("");
  const [message, setMessage] = useState("");

  const handleSend = (e) => {
    e.preventDefault();

    if (!name.trim() || !message.trim()) {
      alert("Please enter your name and message.");
      return;
    }

    const text = `Hello, my name is *${name}*.\n${message}`;
    const url = `https://wa.me/91${settings.mobile}?text=${encodeURIComponent(text)}`;
    window.open(url, "_blank");

    onClose(); // Close modal after sending
    setName("");
    setMessage("");
  };

  // Close on outside click
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (modalRef.current && !modalRef.current.contains(e.target)) {
        onClose();
      }
    };
    if (isOpen) document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div
      ref={modalRef}
      className="absolute bottom-14 right-0 bg-brand-dark shadow-xl border border-gray-300 rounded-md p-4 w-[80vw] lg:w-[30vw]  animate-fade-in"
    >
      <div className="flex justify-between items-center mb-3">
        <h2 className="text-sm lg:text-xl font-semibold text-white">
          Chat with us
        </h2>
        <button onClick={onClose}>
          <X className="w-4 h-4 text-gray-300 hover:text-white" />
        </button>
      </div>
      <form onSubmit={handleSend}>
        <input
          type="text"
          placeholder="Your Name"
          className="w-full mb-2 p-2 lg:py-4 border rounded text-sm"
          value={name}
          onChange={(e) => setName(e.target.value)}
          //   required
        />
        <textarea
          rows={3}
          cols={30}
          placeholder="Your Message"
          className="w-full mb-2 p-2 lg:py-4 border rounded text-sm resize-none"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          //   required
        />
        <button
          type="submit"
          className="w-full bg-brand-gold cursor-pointer text-black font-black py-2 rounded text-sm flex justify-center items-center gap-2"
        >
          <Send size={14} /> Send
        </button>
      </form>
    </div>
  );
}
