"use client";

import { useState, useEffect } from "react";
import { SITE } from "@/lib/config";

type WhatsAppPromptProps = {
  isOpen: boolean;
  onClose: () => void;
  lang: "ar" | "en";
};

export default function WhatsAppPrompt({
  isOpen,
  onClose,
  lang,
}: WhatsAppPromptProps) {
  const [topic, setTopic] = useState("");
  const [message, setMessage] = useState("");

  const isAr = lang === "ar";

  const copy = isAr
    ? {
        title: "كيف يمكننا مساعدتك؟",
        subtitle: "أخبرنا عن احتياجاتك وسنتواصل معك فوراً",
        topicLabel: "اختر الموضوع",
        messageLabel: "رسالتك (اختياري)",
        messagePlaceholder:
          "أضف أي تفاصيل إضافية تساعدنا في خدمتك بشكل أفضل...",
        topics: [
          { value: "demo", label: "أريد عرضاً توضيحياً" },
          { value: "pricing", label: "الاستفسار عن الأسعار" },
          { value: "support", label: "أحتاج دعماً فنياً" },
          { value: "features", label: "أسئلة عن المميزات" },
          { value: "integration", label: "التكامل مع أنظمتي" },
          { value: "other", label: "موضوع آخر" },
        ],
        cancelButton: "إلغاء",
        sendButton: "إرسال عبر واتساب",
        sending: "جاري الإرسال...",
      }
    : {
        title: "How can we help you?",
        subtitle: "Tell us what you need and we'll connect with you right away",
        topicLabel: "Select a topic",
        messageLabel: "Your message (optional)",
        messagePlaceholder:
          "Add any additional details to help us serve you better...",
        topics: [
          { value: "demo", label: "I want a demo" },
          { value: "pricing", label: "Pricing inquiry" },
          { value: "support", label: "Technical support" },
          { value: "features", label: "Questions about features" },
          { value: "integration", label: "Integration with my systems" },
          { value: "other", label: "Something else" },
        ],
        cancelButton: "Cancel",
        sendButton: "Send via WhatsApp",
        sending: "Sending...",
      };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!topic) return;

    // Find the selected topic label
    const selectedTopic =
      copy.topics.find((t) => t.value === topic)?.label || "";

    // Construct the WhatsApp message
    let whatsappMessage = isAr
      ? `مرحباً! أحتاج مساعدة في: ${selectedTopic}`
      : `Hi! I need help with: ${selectedTopic}`;

    if (message) {
      whatsappMessage += isAr
        ? `\n\nتفاصيل إضافية:\n${message}`
        : `\n\nAdditional details:\n${message}`;
    }

    // Encode the message for URL
    const encodedMessage = encodeURIComponent(whatsappMessage);

    // Open WhatsApp with the pre-filled message
    const whatsappUrl = `https://wa.me/${SITE.contact.whatsapp.replace(/[^0-9]/g, "")}?text=${encodedMessage}`;
    window.open(whatsappUrl, "_blank");

    // Reset and close modal
    setTopic("");
    setMessage("");
    onClose();
  };

  // Close on escape key
  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleEscape);
    }

    return () => {
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
        aria-hidden="true"
      />

      {/* Modal */}
      <div className="relative w-full max-w-md rounded-2xl bg-white p-6 shadow-xl">
        {/* Close button */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-1 rounded-lg text-neutral-400 hover:bg-neutral-100 hover:text-neutral-600 transition"
          aria-label={isAr ? "إغلاق" : "Close"}
        >
          <svg
            className="w-5 h-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>

        <div className="space-y-4">
          {/* Header */}
          <div>
            <h2 className="text-xl font-bold text-neutral-900">{copy.title}</h2>
            <p className="mt-1 text-sm text-neutral-600">{copy.subtitle}</p>
          </div>

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Topic Selection */}
            <div>
              <label className="block text-sm font-medium text-neutral-700 mb-2">
                {copy.topicLabel}
              </label>
              <div className="grid grid-cols-2 gap-2">
                {copy.topics.map((topicOption) => (
                  <button
                    key={topicOption.value}
                    type="button"
                    onClick={() => setTopic(topicOption.value)}
                    className={`px-3 py-2 text-sm rounded-lg border transition ${
                      topic === topicOption.value
                        ? "border-brand-green bg-brand-green/10 text-brand-green font-medium"
                        : "border-neutral-200 text-neutral-700 hover:border-neutral-300"
                    }`}
                  >
                    {topicOption.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Optional Message */}
            <div>
              <label
                htmlFor="message"
                className="block text-sm font-medium text-neutral-700 mb-2"
              >
                {copy.messageLabel}
              </label>
              <textarea
                id="message"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                placeholder={copy.messagePlaceholder}
                className="w-full px-3 py-2 text-sm border border-neutral-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-green/20 focus:border-brand-green resize-none"
                rows={3}
                dir={isAr ? "rtl" : "ltr"}
              />
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-2">
              <button
                type="button"
                onClick={onClose}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-neutral-700 bg-neutral-100 rounded-lg hover:bg-neutral-200 transition"
              >
                {copy.cancelButton}
              </button>
              <button
                type="submit"
                disabled={!topic}
                className="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-[#25D366] rounded-lg hover:bg-[#22c55e] disabled:bg-neutral-300 disabled:cursor-not-allowed transition flex items-center justify-center gap-2"
              >
                <svg
                  className="w-4 h-4"
                  fill="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.149-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
                </svg>
                {copy.sendButton}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}
