'use client';

import { User, Phone, Mail, MessageSquare, MapPin, Clock, Send, CheckCircle, AlertCircle, Loader2 } from 'lucide-react';
import { CONTACT_INFO } from '@/config/contact';
import { useState } from 'react';

export default function Contact() {
    const [formData, setFormData] = useState({
        name: '',
        phone: '',
        email: '',
        message: '',
        agreeRobot: false
    });
    const [loading, setLoading] = useState(false);
    const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value, type } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value
        }));
    };

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

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

        if (!formData.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(formData.phone.replace(/\s/g, ''))) {
            setMessage({ type: 'error', text: 'Số điện thoại không hợp lệ' });
            return;
        }

        if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
            setMessage({ type: 'error', text: 'Email không hợp lệ' });
            return;
        }

        if (!formData.message.trim()) {
            setMessage({ type: 'error', text: 'Vui lòng nhập nội dung' });
            return;
        }

        if (!formData.agreeRobot) {
            setMessage({ type: 'error', text: 'Vui lòng xác nhận không phải robot' });
            return;
        }

        setLoading(true);

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

            const data = await response.json();

            if (response.ok) {
                setMessage({ type: 'success', text: data.message });
                // Reset form
                setFormData({
                    name: '',
                    phone: '',
                    email: '',
                    message: '',
                    agreeRobot: false
                });
            } 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);
        }
    };

    const contactInfo = [
        {
            icon: <Phone className="w-6 h-6" />,
            title: "Hotline",
            value: CONTACT_INFO.phone.display,
            link: CONTACT_INFO.phone.href,
            gradient: "from-blue-500 to-blue-600"
        },
        {
            icon: <Mail className="w-6 h-6" />,
            title: "Email",
            value: CONTACT_INFO.email.display,
            link: CONTACT_INFO.email.href,
            gradient: "from-red-500 to-red-600"
        },
        {
            icon: <MapPin className="w-6 h-6" />,
            title: "Địa chỉ",
            value: CONTACT_INFO.address.short,
            link: "#",
            gradient: "from-green-500 to-green-600"
        },
        {
            icon: <Clock className="w-6 h-6" />,
            title: "Giờ làm việc",
            value: `${CONTACT_INFO.workingHours.weekday}`,
            link: "#",
            gradient: "from-purple-500 to-purple-600"
        }
    ];

    return (
        <section className="relative bg-white py-8 xs:py-10 sm:py-12 md:py-16 lg:py-20 overflow-hidden">
            {/* Background decoration */}
            <div className="absolute inset-0 pointer-events-none">
                <div className="absolute top-0 right-0 w-96 h-96 bg-red-100 rounded-full blur-3xl opacity-30" />
                <div className="absolute bottom-0 left-0 w-96 h-96 bg-yellow-100 rounded-full blur-3xl opacity-30" />
            </div>

            <div className="container relative z-10">
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 items-start">
                    <div className="space-y-8">
                        <div className="space-y-4">
                            <span className="inline-block text-red-500 font-bold text-sm md:text-base uppercase tracking-widest bg-red-50 px-4 py-2 rounded-full">
                                Liên Hệ
                            </span>
                            <h2 className="text-3xl md:text-5xl font-bold text-neutral-900 leading-tight">
                                Bắt Đầu Dự Án <br />
                                <span className="text-red-500">Của Bạn Ngay</span>
                            </h2>
                            <p className="text-neutral-600 text-lg leading-relaxed">
                                Hãy chia sẻ ý tưởng của bạn với chúng tôi.
                                <span className="font-bold text-red-600"> V_LOG </span>
                                <span className="font-bold text-black">MEDIA </span>
                                sẵn sàng đồng hành cùng bạn để biến những ý tưởng thành hiện thực.
                            </p>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {contactInfo.map((item, index) => (
                                <a
                                    key={index}
                                    href={item.link}
                                    className="group bg-white border-2 border-neutral-100 rounded-2xl p-5 hover:border-red-500 hover:shadow-lg transition-all duration-300"
                                >
                                    <div className="flex items-start gap-4">
                                        <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${item.gradient} flex items-center justify-center text-white flex-shrink-0 group-hover:scale-110 transition-transform duration-300 shadow-md`}>
                                            {item.icon}
                                        </div>
                                        <div className="flex-1 min-w-0">
                                            <h4 className="text-sm font-semibold text-neutral-500 mb-1">
                                                {item.title}
                                            </h4>
                                            <p className="text-neutral-900 font-semibold text-sm truncate">
                                                {item.value}
                                            </p>
                                        </div>
                                    </div>
                                </a>
                            ))}
                        </div>

                        {/* Additional Info */}
                        <div className="bg-gradient-to-br from-red-50 to-orange-50 rounded-2xl p-6 border-2 border-red-100">
                            <div className="flex items-start gap-4">
                                <div className="w-12 h-12 bg-red-500 rounded-xl flex items-center justify-center flex-shrink-0">
                                    <CheckCircle className="w-6 h-6 text-white" />
                                </div>
                                <div>
                                    <h4 className="font-bold text-neutral-900 mb-2">
                                        Tư Vấn Miễn Phí
                                    </h4>
                                    <p className="text-neutral-600 text-sm leading-relaxed">
                                        Chúng tôi cung cấp dịch vụ tư vấn miễn phí để giúp bạn chọn
                                        gói dịch vụ phù hợp nhất với nhu cầu và ngân sách.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Right Column - Form */}
                    <div>
                        <form
                            onSubmit={handleSubmit}
                            className="bg-white border-2 border-neutral-100 rounded-3xl p-8 shadow-xl hover:shadow-2xl transition-shadow duration-300"
                        >
                            <div className="space-y-4 sm:space-y-5 md:space-y-6">
                                {/* Name Input */}
                                <div className="relative">
                                    <label htmlFor="name" className="block text-xs xs:text-sm md:text-base font-semibold text-neutral-700 mb-2">
                                        Họ và tên <span className="text-red-500">*</span>
                                    </label>
                                    <div className="relative">
                                        <User className="absolute left-3 xs:left-4 top-1/2 -translate-y-1/2 text-neutral-400 w-4 h-4 xs:w-5 xs:h-5" />
                                        <input
                                            id="name"
                                            type="text"
                                            name="name"
                                            value={formData.name}
                                            onChange={handleInputChange}
                                            required
                                            placeholder="Nhập họ và tên của bạn"
                                            className="pl-10 xs:pl-12 pr-3 xs:pr-4 py-3 xs:py-3.5 sm:py-4 rounded-xl border-2 border-neutral-200 w-full focus:outline-none focus:border-red-500 transition-all duration-200 hover:border-neutral-300 text-sm xs:text-base placeholder:text-xs xs:placeholder:text-sm"
                                            disabled={loading}
                                        />
                                    </div>
                                </div>

                                {/* Phone & Email */}
                                <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 gap-3 xs:gap-4 md:gap-4">
                                    <div className="relative">
                                        <label htmlFor="phone" className="block text-xs xs:text-sm md:text-base font-semibold text-neutral-700 mb-2">
                                            Số điện thoại <span className="text-red-500">*</span>
                                        </label>
                                        <div className="relative">
                                            <Phone className="absolute left-3 xs:left-4 top-1/2 -translate-y-1/2 text-neutral-400 w-4 h-4 xs:w-5 xs:h-5" />
                                            <input
                                                id="phone"
                                                type="tel"
                                                name="phone"
                                                value={formData.phone}
                                                onChange={handleInputChange}
                                                required
                                                placeholder="0912 345 678"
                                                className="pl-10 xs:pl-12 pr-3 xs:pr-4 py-3 xs:py-3.5 sm:py-4 rounded-xl border-2 border-neutral-200 w-full focus:outline-none focus:border-red-500 transition-all duration-200 hover:border-neutral-300 text-sm xs:text-base placeholder:text-xs xs:placeholder:text-sm"
                                                disabled={loading}
                                            />
                                        </div>
                                    </div>

                                    <div className="relative">
                                        <label htmlFor="email" className="block text-xs xs:text-sm md:text-base font-semibold text-neutral-700 mb-2">
                                            Email
                                        </label>
                                        <div className="relative">
                                            <Mail className="absolute left-3 xs:left-4 top-1/2 -translate-y-1/2 text-neutral-400 w-4 h-4 xs:w-5 xs:h-5" />
                                            <input
                                                id="email"
                                                type="email"
                                                name="email"
                                                value={formData.email}
                                                onChange={handleInputChange}
                                                placeholder="email@example.com"
                                                className="pl-10 xs:pl-12 pr-3 xs:pr-4 py-3 xs:py-3.5 sm:py-4 rounded-xl border-2 border-neutral-200 w-full focus:outline-none focus:border-red-500 transition-all duration-200 hover:border-neutral-300 text-sm xs:text-base placeholder:text-xs xs:placeholder:text-sm"
                                                disabled={loading}
                                            />
                                        </div>
                                    </div>
                                </div>

                                {/* Message */}
                                <div className="relative">
                                    <label htmlFor="message" className="block text-xs xs:text-sm md:text-base font-semibold text-neutral-700 mb-2">
                                        Nội dung <span className="text-red-500">*</span>
                                    </label>
                                    <div className="relative">
                                        <MessageSquare className="absolute left-3 xs:left-4 top-3 xs:top-4 text-neutral-400 w-4 h-4 xs:w-5 xs:h-5" />
                                        <textarea
                                            id="message"
                                            name="message"
                                            value={formData.message}
                                            onChange={handleInputChange}
                                            required
                                            placeholder="Cho chúng tôi biết chi tiết về dự án của bạn..."
                                            rows={5}
                                            className="pl-10 xs:pl-12 pr-3 xs:pr-4 py-3 xs:py-4 w-full rounded-xl border-2 border-neutral-200 focus:outline-none focus:border-red-500 transition-all duration-200 hover:border-neutral-300 resize-none text-sm xs:text-base placeholder:text-xs xs:placeholder:text-sm"
                                            disabled={loading}
                                        ></textarea>
                                    </div>
                                </div>

                                {/* Captcha */}
                                <label className="bg-neutral-50 px-5 py-4 rounded-xl border-2 border-neutral-200 flex items-center gap-3 cursor-pointer hover:bg-neutral-100 transition-colors">
                                    <input
                                        type="checkbox"
                                        name="agreeRobot"
                                        checked={formData.agreeRobot}
                                        onChange={handleInputChange}
                                        required
                                        className="accent-red-600 w-5 h-5"
                                        disabled={loading}
                                    />
                                    <span className="text-sm text-neutral-700 font-medium">
                                        Tôi không phải là robot
                                    </span>
                                    <span className="ml-auto text-xs text-neutral-400 font-semibold">
                                        CLOUDFLARE
                                    </span>
                                </label>

                                {/* Message */}
                                {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>
                                )}

                                {/* Submit Button */}
                                <button
                                    type="submit"
                                    disabled={loading}
                                    className={`w-full py-4 rounded-xl font-bold text-lg transition-all duration-300 flex items-center justify-center gap-2 ${loading
                                            ? 'bg-gray-400 text-white cursor-not-allowed'
                                            : 'bg-gradient-to-r from-red-500 to-red-600 text-white hover:from-red-600 hover:to-red-700 hover:shadow-lg hover:scale-105'
                                        }`}
                                >
                                    {loading ? (
                                        <>
                                            <Loader2 className="w-5 h-5 animate-spin" />
                                            Đang gửi...
                                        </>
                                    ) : (
                                        <>
                                            <Send className="w-5 h-5" />
                                            Gửi Thông Tin
                                        </>
                                    )}
                                </button>

                                <p className="text-xs text-neutral-500 text-center">
                                    Bằng cách gửi biểu mẫu này, bạn đồng ý với{' '}
                                    <a href="#" className="text-red-500 hover:underline">
                                        chính sách bảo mật
                                    </a>{' '}
                                    của chúng tôi.
                                </p>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    );
}
