"use client";

import { CheckCircle, AlertCircle, Loader2 } from "lucide-react";
import { useEffect, useState } from "react";

interface ConsultModalProps {
    show: boolean;
    onClose: () => void;
}

const ConsultModal = ({ show, onClose }: ConsultModalProps) => {
    const [name, setName] = useState("");
    const [phone, setPhone] = useState("");
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

    useEffect(() => {
        const handleEsc = (e: KeyboardEvent) => {
            if (e.key === "Escape") onClose();
        };
        document.addEventListener("keydown", handleEsc);
        return () => document.removeEventListener("keydown", handleEsc);
    }, [onClose]);

    useEffect(() => {
        if (!show) {
            setTimeout(() => {
                setName("");
                setPhone("");
                setMessage(null);
            }, 300);
        }
    }, [show]);

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

        if (!name.trim()) {
            setMessage({ type: "error", text: "Vui lòng nhập họ tên" });
            return;
        }

        if (!phone.trim()) {
            setMessage({ type: "error", text: "Vui lòng nhập số điện thoại" });
            return;
        }

        const phoneRegex = /^(0|\+84)(3|5|7|8|9)[0-9]{8}$/;
        if (!phoneRegex.test(phone.replace(/\s/g, ""))) {
            setMessage({ type: "error", text: "Số điện thoại không hợp lệ" });
            return;
        }

        setLoading(true);

        try {
            const response = await fetch("/api/send-email", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ name: name.trim(), phone: phone.trim() }),
            });

            const data = await response.json();

            if (response.ok) {
                setMessage({ type: "success", text: data.message });
                setTimeout(() => {
                    onClose();
                }, 2000);
            } else {
                setMessage({ type: "error", text: data.error || "Có lỗi xảy ra" });
            }
        } catch (error) {
            setMessage({ type: "error", text: "Không thể kết nối. Vui lòng thử lại" });
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            {show && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm"
                    onClick={onClose}
                >
                    <div
                        className="relative bg-gradient-to-br from-white via-pink-50 to-blue-50 rounded-2xl shadow-2xl p-12 w-[90%] md:w-[800px] flex flex-col md:flex-row gap-6"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <button
                            onClick={onClose}
                            className="absolute top-3 right-3 text-gray-500 hover:text-red-600 text-2xl transition-colors"
                            disabled={loading}
                        >
                            ✕
                        </button>

                        <div className="flex-1 flex flex-col justify-center items-center gap-1">
                            <div className="flex items-center gap-2">
                                <span className="text-4xl font-extrabold text-red-600 drop-shadow-lg">
                                    V_LOG
                                </span>
                                <span className="text-4xl font-extrabold text-gray-900 drop-shadow-lg">
                                    MEDIA
                                </span>
                            </div>
                            <p className="text-sm text-gray-600 italic text-center">
                                Chúng tôi ở đây để đồng hành cùng thương hiệu của bạn.
                            </p>
                        </div>

                        <form onSubmit={handleSubmit} className="flex-1 flex flex-col justify-center gap-4">
                            <h2 className="text-2xl font-bold text-gray-800">
                                NHẬN{" "}
                                <span className="bg-red-600 text-white px-2 py-1 rounded">
                                    TƯ VẤN, BÁO GIÁ
                                </span>
                            </h2>

                            <input
                                type="text"
                                placeholder="Nhập họ tên khách hàng"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                className="px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-red-500 outline-none transition-all"
                                disabled={loading}
                            />

                            <input
                                type="text"
                                placeholder="Số điện thoại (VD: 0901234567)"
                                value={phone}
                                onChange={(e) => setPhone(e.target.value)}
                                className="px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-red-500 outline-none transition-all"
                                disabled={loading}
                            />

                            {message && (
                                <div
                                    className={`flex items-center gap-2 p-3 rounded-lg ${message.type === "success"
                                            ? "bg-green-50 text-green-700 border border-green-200"
                                            : "bg-red-50 text-red-700 border border-red-200"
                                        }`}
                                >
                                    {message.type === "success" ? (
                                        <CheckCircle className="w-5 h-5 flex-shrink-0" />
                                    ) : (
                                        <AlertCircle className="w-5 h-5 flex-shrink-0" />
                                    )}
                                    <span className="text-sm font-medium">{message.text}</span>
                                </div>
                            )}

                            <button
                                type="submit"
                                disabled={loading}
                                className="bg-gradient-to-r from-red-600 to-pink-500 text-white py-3 rounded-full shadow-md font-semibold hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                            >
                                {loading ? (
                                    <>
                                        <Loader2 className="w-5 h-5 animate-spin" />
                                        Đang gửi...
                                    </>
                                ) : (
                                    "Gửi ngay"
                                )}
                            </button>
                        </form>
                    </div>
                </div>
            )}
        </>
    );
};

export default ConsultModal;
