'use client';

import { useState, useRef, useEffect } from "react";
import { useRouter } from "next/navigation";
import gsap from "gsap";
import { useSignup } from "@/hooks/useAuth";
import { EyeIcon, EyeSlashIcon } from "@heroicons/react/24/outline";


const countryData = [
    { name: "Afghanistan", dial_code: "+93", code: "AF" },
    { name: "Albania", dial_code: "+355", code: "AL" },
    { name: "Algeria", dial_code: "+213", code: "DZ" },
    { name: "Andorra", dial_code: "+376", code: "AD" },
    { name: "Angola", dial_code: "+244", code: "AO" },
    { name: "Antigua and Barbuda", dial_code: "+1-268", code: "AG" },
    { name: "Argentina", dial_code: "+54", code: "AR" },
    { name: "Armenia", dial_code: "+374", code: "AM" },
    { name: "Australia", dial_code: "+61", code: "AU" },
    { name: "Austria", dial_code: "+43", code: "AT" },
    { name: "Azerbaijan", dial_code: "+994", code: "AZ" },
    { name: "Bahamas", dial_code: "+1-242", code: "BS" },
    { name: "Bahrain", dial_code: "+973", code: "BH" },
    { name: "Bangladesh", dial_code: "+880", code: "BD" },
    { name: "Barbados", dial_code: "+1-246", code: "BB" },
    { name: "Belarus", dial_code: "+375", code: "BY" },
    { name: "Belgium", dial_code: "+32", code: "BE" },
    { name: "Belize", dial_code: "+501", code: "BZ" },
    { name: "Benin", dial_code: "+229", code: "BJ" },
    { name: "Bhutan", dial_code: "+975", code: "BT" },
    { name: "Bolivia", dial_code: "+591", code: "BO" },
    { name: "Bosnia and Herzegovina", dial_code: "+387", code: "BA" },
    { name: "Botswana", dial_code: "+267", code: "BW" },
    { name: "Brazil", dial_code: "+55", code: "BR" },
    { name: "Brunei", dial_code: "+673", code: "BN" },
    { name: "Bulgaria", dial_code: "+359", code: "BG" },
    { name: "Burkina Faso", dial_code: "+226", code: "BF" },
    { name: "Burundi", dial_code: "+257", code: "BI" },
    { name: "Cambodia", dial_code: "+855", code: "KH" },
    { name: "Cameroon", dial_code: "+237", code: "CM" },
    { name: "Canada", dial_code: "+1", code: "CA" },
    { name: "Cape Verde", dial_code: "+238", code: "CV" },
    { name: "Central African Republic", dial_code: "+236", code: "CF" },
    { name: "Chad", dial_code: "+235", code: "TD" },
    { name: "Chile", dial_code: "+56", code: "CL" },
    { name: "China", dial_code: "+86", code: "CN" },
    { name: "Colombia", dial_code: "+57", code: "CO" },
    { name: "Comoros", dial_code: "+269", code: "KM" },
    { name: "Congo", dial_code: "+242", code: "CG" },
    { name: "Costa Rica", dial_code: "+506", code: "CR" },
    { name: "Croatia", dial_code: "+385", code: "HR" },
    { name: "Cuba", dial_code: "+53", code: "CU" },
    { name: "Cyprus", dial_code: "+357", code: "CY" },
    { name: "Czech Republic", dial_code: "+420", code: "CZ" },
    { name: "Denmark", dial_code: "+45", code: "DK" },
    { name: "Djibouti", dial_code: "+253", code: "DJ" },
    { name: "Dominica", dial_code: "+1-767", code: "DM" },
    { name: "Dominican Republic", dial_code: "+1-809, +1-829, +1-849", code: "DO" },
    { name: "Ecuador", dial_code: "+593", code: "EC" },
    { name: "Egypt", dial_code: "+20", code: "EG" },
    { name: "El Salvador", dial_code: "+503", code: "SV" },
    { name: "Equatorial Guinea", dial_code: "+240", code: "GQ" },
    { name: "Eritrea", dial_code: "+291", code: "ER" },
    { name: "Estonia", dial_code: "+372", code: "EE" },
    { name: "Eswatini", dial_code: "+268", code: "SZ" },
    { name: "Ethiopia", dial_code: "+251", code: "ET" },
    { name: "Fiji", dial_code: "+679", code: "FJ" },
    { name: "Finland", dial_code: "+358", code: "FI" },
    { name: "France", dial_code: "+33", code: "FR" },
    { name: "Gabon", dial_code: "+241", code: "GA" },
    { name: "Gambia", dial_code: "+220", code: "GM" },
    { name: "Georgia", dial_code: "+995", code: "GE" },
    { name: "Germany", dial_code: "+49", code: "DE" },
    { name: "Ghana", dial_code: "+233", code: "GH" },
    { name: "Greece", dial_code: "+30", code: "GR" },
    { name: "Grenada", dial_code: "+1-473", code: "GD" },
    { name: "Guatemala", dial_code: "+502", code: "GT" },
    { name: "Guinea", dial_code: "+224", code: "GN" },
    { name: "Guinea-Bissau", dial_code: "+245", code: "GW" },
    { name: "Guyana", dial_code: "+592", code: "GY" },
    { name: "Haiti", dial_code: "+509", code: "HT" },
    { name: "Honduras", dial_code: "+504", code: "HN" },
    { name: "Hungary", dial_code: "+36", code: "HU" },
    { name: "Iceland", dial_code: "+354", code: "IS" },
    { name: "India", dial_code: "+91", code: "IN" },
    { name: "Indonesia", dial_code: "+62", code: "ID" },
    { name: "Iran", dial_code: "+98", code: "IR" },
    { name: "Iraq", dial_code: "+964", code: "IQ" },
    { name: "Ireland", dial_code: "+353", code: "IE" },
    { name: "Israel", dial_code: "+972", code: "IL" },
    { name: "Italy", dial_code: "+39", code: "IT" },
    { name: "Jamaica", dial_code: "+1-876", code: "JM" },
    { name: "Japan", dial_code: "+81", code: "JP" },
    { name: "Jordan", dial_code: "+962", code: "JO" },
    { name: "Kazakhstan", dial_code: "+7", code: "KZ" },
    { name: "Kenya", dial_code: "+254", code: "KE" },
    { name: "Kiribati", dial_code: "+686", code: "KI" },
    { name: "Korea, North", dial_code: "+850", code: "KP" },
    { name: "Korea, South", dial_code: "+82", code: "KR" },
    { name: "Kosovo", dial_code: "+383", code: "XK" },
    { name: "Kuwait", dial_code: "+965", code: "KW" },
    { name: "Kyrgyzstan", dial_code: "+996", code: "KG" },
    { name: "Laos", dial_code: "+856", code: "LA" },
    { name: "Latvia", dial_code: "+371", code: "LV" },
    { name: "Lebanon", dial_code: "+961", code: "LB" },
    { name: "Lesotho", dial_code: "+266", code: "LS" },
    { name: "Liberia", dial_code: "+231", code: "LR" },
    { name: "Libya", dial_code: "+218", code: "LY" },
    { name: "Liechtenstein", dial_code: "+423", code: "LI" },
    { name: "Lithuania", dial_code: "+370", code: "LT" },
    { name: "Luxembourg", dial_code: "+352", code: "LU" },
    { name: "Madagascar", dial_code: "+261", code: "MG" },
    { name: "Malawi", dial_code: "+265", code: "MW" },
    { name: "Malaysia", dial_code: "+60", code: "MY" },
    { name: "Maldives", dial_code: "+960", code: "MV" },
    { name: "Mali", dial_code: "+223", code: "ML" },
    { name: "Malta", dial_code: "+356", code: "MT" },
    { name: "Marshall Islands", dial_code: "+692", code: "MH" },
    { name: "Mauritania", dial_code: "+222", code: "MR" },
    { name: "Mauritius", dial_code: "+230", code: "MU" },
    { name: "Mexico", dial_code: "+52", code: "MX" },
    { name: "Micronesia", dial_code: "+691", code: "FM" },
    { name: "Moldova", dial_code: "+373", code: "MD" },
    { name: "Monaco", dial_code: "+377", code: "MC" },
    { name: "Mongolia", dial_code: "+976", code: "MN" },
    { name: "Montenegro", dial_code: "+382", code: "ME" },
    { name: "Morocco", dial_code: "+212", code: "MA" },
    { name: "Mozambique", dial_code: "+258", code: "MZ" },
    { name: "Myanmar", dial_code: "+95", code: "MM" },
    { name: "Namibia", dial_code: "+264", code: "NA" },
    { name: "Nauru", dial_code: "+674", code: "NR" },
    { name: "Nepal", dial_code: "+977", code: "NP" },
    { name: "Netherlands", dial_code: "+31", code: "NL" },
    { name: "New Zealand", dial_code: "+64", code: "NZ" },
    { name: "Nicaragua", dial_code: "+505", code: "NI" },
    { name: "Niger", dial_code: "+227", code: "NE" },
    { name: "Nigeria", dial_code: "+234", code: "NG" },
    { name: "North Macedonia", dial_code: "+389", code: "MK" },
    { name: "Norway", dial_code: "+47", code: "NO" },
    { name: "Oman", dial_code: "+968", code: "OM" },
    { name: "Pakistan", dial_code: "+92", code: "PK" },
    { name: "Palau", dial_code: "+680", code: "PW" },
    { name: "Panama", dial_code: "+507", code: "PA" },
    { name: "Papua New Guinea", dial_code: "+675", code: "PG" },
    { name: "Paraguay", dial_code: "+595", code: "PY" },
    { name: "Peru", dial_code: "+51", code: "PE" },
    { name: "Philippines", dial_code: "+63", code: "PH" },
    { name: "Poland", dial_code: "+48", code: "PL" },
    { name: "Portugal", dial_code: "+351", code: "PT" },
    { name: "Qatar", dial_code: "+974", code: "QA" },
    { name: "Romania", dial_code: "+40", code: "RO" },
    { name: "Russia", dial_code: "+7", code: "RU" },
    { name: "Rwanda", dial_code: "+250", code: "RW" },
    { name: "Saint Kitts and Nevis", dial_code: "+1-869", code: "KN" },
    { name: "Saint Lucia", dial_code: "+1-758", code: "LC" },
    { name: "Saint Vincent and the Grenadines", dial_code: "+1-784", code: "VC" },
    { name: "Samoa", dial_code: "+685", code: "WS" },
    { name: "San Marino", dial_code: "+378", code: "SM" },
    { name: "Sao Tome and Principe", dial_code: "+239", code: "ST" },
    { name: "Saudi Arabia", dial_code: "+966", code: "SA" },
    { name: "Senegal", dial_code: "+221", code: "SN" },
    { name: "Serbia", dial_code: "+381", code: "RS" },
    { name: "Seychelles", dial_code: "+248", code: "SC" },
    { name: "Sierra Leone", dial_code: "+232", code: "SL" },
    { name: "Singapore", dial_code: "+65", code: "SG" },
    { name: "Slovakia", dial_code: "+421", code: "SK" },
    { name: "Slovenia", dial_code: "+386", code: "SI" },
    { name: "Solomon Islands", dial_code: "+677", code: "SB" },
    { name: "Somalia", dial_code: "+252", code: "SO" },
    { name: "South Africa", dial_code: "+27", code: "ZA" },
    { name: "South Sudan", dial_code: "+211", code: "SS" },
    { name: "Spain", dial_code: "+34", code: "ES" },
    { name: "Sri Lanka", dial_code: "+94", code: "LK" },
    { name: "Sudan", dial_code: "+249", code: "SD" },
    { name: "Suriname", dial_code: "+597", code: "SR" },
    { name: "Sweden", dial_code: "+46", code: "SE" },
    { name: "Switzerland", dial_code: "+41", code: "CH" },
    { name: "Syria", dial_code: "+963", code: "SY" },
    { name: "Taiwan", dial_code: "+886", code: "TW" },
    { name: "Tajikistan", dial_code: "+992", code: "TJ" },
    { name: "Tanzania", dial_code: "+255", code: "TZ" },
    { name: "Thailand", dial_code: "+66", code: "TH" },
    { name: "Togo", dial_code: "+228", code: "TG" },
    { name: "Tonga", dial_code: "+676", code: "TO" },
    { name: "Trinidad and Tobago", dial_code: "+1-868", code: "TT" },
    { name: "Tunisia", dial_code: "+216", code: "TN" },
    { name: "Turkey", dial_code: "+90", code: "TR" },
    { name: "Turkmenistan", dial_code: "+993", code: "TM" },
    { name: "Tuvalu", dial_code: "+688", code: "TV" },
    { name: "Uganda", dial_code: "+256", code: "UG" },
    { name: "Ukraine", dial_code: "+380", code: "UA" },
    { name: "United Arab Emirates", dial_code: "+971", code: "AE" },
    { name: "United Kingdom", dial_code: "+44", code: "GB" },
    { name: "United States", dial_code: "+1", code: "US" },
    { name: "Uruguay", dial_code: "+598", code: "UY" },
    { name: "Uzbekistan", dial_code: "+998", code: "UZ" },
    { name: "Vanuatu", dial_code: "+678", code: "VU" },
    { name: "Vatican City", dial_code: "+379", code: "VA" },
    { name: "Venezuela", dial_code: "+58", code: "VE" },
    { name: "Vietnam", dial_code: "+84", code: "VN" },
    { name: "Yemen", dial_code: "+967", code: "YE" },
    { name: "Zambia", dial_code: "+260", code: "ZM" },
    { name: "Zimbabwe", dial_code: "+263", code: "ZW" }
];

export default function RegisterPage() {
    const formRef = useRef(null);
    const router = useRouter();
    const [step, setStep] = useState(1);
    const [role, setRole] = useState("patient");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [errors, setErrors] = useState({});
    const [showPassword, setShowPassword] = useState(false);
    const { mutate: signup } = useSignup();

    const [formData, setFormData] = useState({
        firstName: "", lastName: "", email: "",
        password: "", licenceNumber: "", labName: "",
        pharmacyName: "", phone: "", countryCode: "+1",
        country: "", terms: false,
    });

    useEffect(() => {
        gsap.fromTo(
            formRef.current,
            { opacity: 0, y: 40 },
            { opacity: 1, y: 0, duration: 1.2, ease: "power3.out" }
        );
    }, [step]);

    const roles = {
        patient: "Individual seeking consultations",
        doctor: "Diaspora doctor or nurse",
        lab: "Lab uploading test results",
        pharmacy: "Pharmacy receiving prescriptions",
    };

    const validateStep = () => {
        const e = {};
        if (step === 1) {
            // always valid
        }
        if (step === 2) {
            if (!formData.firstName.trim()) e.firstName = "First name is required.";
            if (!formData.lastName.trim()) e.lastName = "Last name is required.";
            if (!/\S+@\S+\.\S+/.test(formData.email)) e.email = "Invalid email.";
            if (formData.phone.trim().length < 5) e.phone = "Invalid phone.";
            if (!formData.country) e.country = "Select your country.";
            if (formData.password.length < 8) e.password = "Min 8 characters.";
            if (role === "doctor" && !formData.licenceNumber.trim())
                e.licenceNumber = "Licence can't be blank.";
            if (role === "lab" && !formData.labName.trim())
                e.labName = "Lab name required.";
            if (role === "pharmacy" && !formData.pharmacyName.trim())
                e.pharmacyName = "Pharmacy name required.";
        }
        if (step === 3) {
            if (!formData.terms) e.terms = "You must agree to terms.";
        }
        setErrors(e);
        return Object.keys(e).length === 0;
    };

    const handleChange = (e) => {
        const { name, value, type, checked } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === "checkbox" ? checked : value,
        }));
        setErrors(prev => ({ ...prev, [name]: "" }));
    };

    const nextStep = () => {
        if (validateStep()) setStep(s => s + 1);
    };
    const prevStep = () => setStep(s => Math.max(s - 1, 1));

    const handleSubmit = (e) => {
        e.preventDefault();
        if (!validateStep()) return;

        setIsSubmitting(true);
        const fullPhone = (formData.countryCode + formData.phone).replace(/\s/g, "");

        signup({
            role, ...formData, phone: fullPhone
        }, {
            onSuccess: data => {
                router.push(`/verify-email?email=${encodeURIComponent(formData.email)}&phone=${encodeURIComponent(fullPhone)}`);
            },
            onError: err => {
                setErrors({ form: err.message || "Registration failed." });
                setIsSubmitting(false);
            }
        });
    };

    return (
        <section className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100 p-6">
            <div ref={formRef} className="max-w-2xl w-full bg-white p-8 rounded-2xl shadow-lg border border-blue-100">
                <form onSubmit={handleSubmit} className="space-y-6">
                    {errors.form && <p className="text-red-600">{errors.form}</p>}

                    {step < 4 && <>
                        <h2 className="text-2xl font-bold text-blue-900">{step === 1 ? 'Create Your Account' : step === 3 ? 'Almost There!' : 'Enter Your Details'}</h2>
                        <p className="text-blue-800">{roles[role]}</p>
                    </>}

                    {step === 1 && (
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                            {Object.keys(roles).map(r => (
                                <button
                                    key={r}
                                    type="button"
                                    onClick={() => setRole(r)}
                                    className={`${role === r ? 'bg-blue-800 text-white' : 'bg-white border'} rounded-lg py-2`}
                                >
                                    {r.charAt(0).toUpperCase() + r.slice(1)}
                                </button>
                            ))}
                            <div className="md:col-span-4 flex justify-end mt-4">
                                <button type="button" onClick={nextStep} className="bg-blue-800 text-white px-5 py-2 rounded-lg">Next</button>
                            </div>
                        </div>
                    )}

                    {step === 2 && (
                        <>
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <input name="firstName" value={formData.firstName} onChange={handleChange}
                                        placeholder="First Name" className={`w-full p-3 rounded-lg border ${errors.firstName ? 'border-red-400' : 'border-gray-300'}`} />
                                    {errors.firstName && <p className="text-red-500 text-sm">{errors.firstName}</p>}
                                </div>
                                <div>
                                    <input name="lastName" value={formData.lastName} onChange={handleChange}
                                        placeholder="Last Name" className={`w-full p-3 rounded-lg border ${errors.lastName ? 'border-red-400' : 'border-gray-300'}`} />
                                    {errors.lastName && <p className="text-red-500 text-sm">{errors.lastName}</p>}
                                </div>
                            </div>
                            <div>
                                <input name="email" type="email" value={formData.email} onChange={handleChange}
                                    placeholder="Email Address" className={`w-full p-3 rounded-lg border ${errors.email ? 'border-red-400' : 'border-gray-300'}`} />
                                {errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
                            </div>

                            <div className="flex gap-2">
                                <select name="countryCode" value={formData.countryCode} onChange={handleChange}
                                    className="w-1/3 p-3 rounded-lg border">
                                    {countryData.map((c) => (
                                        <option key={c.code} value={c.dial_code}>
                                            {c.name} {c.dial_code}
                                        </option>
                                    ))}                </select>
                                <div className="w-2/3">
                                    <input name="phone" value={formData.phone} onChange={handleChange}
                                        placeholder="Phone Number" className={`w-full p-3 rounded-lg border ${errors.phone ? 'border-red-400' : 'border-gray-300'}`} />
                                    {errors.phone && <p className="text-red-500 text-sm">{errors.phone}</p>}
                                </div>
                            </div>

                            <div>
                                <select name="country" value={formData.country} onChange={handleChange}
                                    className={`w-full p-3 rounded-lg border ${errors.country ? 'border-red-400' : 'border-gray-300'}`}>
                                    <option value="">-- Select Country --</option>
                                    {countryData.map((c) => (
                                        <option key={c.code} value={c.name}>
                                            {c.name}
                                        </option>
                                    ))}
                                </select>
                                {errors.country && <p className="text-red-500 text-sm">{errors.country}</p>}
                            </div>

                            <div className="relative">
                                <input name="password" type={showPassword ? "text" : "password"} value={formData.password} onChange={handleChange}
                                    placeholder="Password" className={`w-full p-3 rounded-lg border pr-12 ${errors.password ? 'border-red-400' : 'border-gray-300'}`} />
                                <button type="button" onClick={() => setShowPassword(p => !p)} className="absolute inset-y-0 right-3 flex items-center text-gray-500">
                                    {showPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                                </button>
                                {errors.password && <p className="text-red-500 text-sm">{errors.password}</p>}
                            </div>

                            {role === "doctor" && <>
                                <input name="licenceNumber" value={formData.licenceNumber} onChange={handleChange}
                                    placeholder="Medical Licence Number" className={`w-full p-3 rounded-lg border ${errors.licenceNumber ? 'border-red-400' : 'border-gray-300'}`} />
                                {errors.licenceNumber && <p className="text-red-500 text-sm">{errors.licenceNumber}</p>}
                            </>}
                            {role === "lab" && <>
                                <input name="labName" value={formData.labName} onChange={handleChange}
                                    placeholder="Laboratory Name" className={`w-full p-3 rounded-lg border ${errors.labName ? 'border-red-400' : 'border-gray-300'}`} />
                                {errors.labName && <p className="text-red-500 text-sm">{errors.labName}</p>}
                            </>}
                            {role === "pharmacy" && <>
                                <input name="pharmacyName" value={formData.pharmacyName} onChange={handleChange}
                                    placeholder="Pharmacy Name" className={`w-full p-3 rounded-lg border ${errors.pharmacyName ? 'border-red-400' : 'border-gray-300'}`} />
                                {errors.pharmacyName && <p className="text-red-500 text-sm">{errors.pharmacyName}</p>}
                            </>}

                            <div className="flex justify-between">
                                <button type="button" onClick={prevStep} className="text-blue-700 hover:underline">Back</button>
                                <button type="button" onClick={nextStep} className="bg-blue-800 text-white px-5 py-2 rounded-lg">Next</button>
                            </div>
                        </>
                    )}

                    {step === 3 && (
                        <>
                            <div>
                                <label className="inline-flex items-center gap-2">
                                    <input type="checkbox" name="terms" checked={formData.terms} onChange={handleChange} className="form-checkbox" />
                                    <span>
                                        I agree to the{" "}
                                        <a
                                            href={
                                                role === "doctor"
                                                    ? "/termsdoctors"
                                                    : role === "lab" || role === "pharmacy"
                                                        ? "/termslabpharmacy"
                                                        : "/terms"
                                            }
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="underline text-blue-700"
                                        >
                                            Terms & Conditions
                                        </a>
                                    </span>

                                    {(role === "doctor" || role === "lab" || role === "pharmacy") && (
                                        <span>
                                            I agree to the{" "}
                                            <a
                                                href={
                                                    role === "doctor"
                                                        ? `/agreementdoctor?firstName=${encodeURIComponent(formData.firstName)}&lastName=${encodeURIComponent(formData.lastName)}&licenceNumber=${encodeURIComponent(formData.licenceNumber)}&country=${encodeURIComponent(formData.country)}`
                                                        : `/agreementlabpharmacy?firstName=${encodeURIComponent(formData.firstName)}&lastName=${encodeURIComponent(formData.lastName)}&pharmacyName=${encodeURIComponent(formData.pharmacyName)}&labName=${encodeURIComponent(formData.labName)}&country=${encodeURIComponent(formData.country)}`
                                                }
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="underline text-blue-700"
                                            >
                                                {role === "doctor" ? "Confidentiality Agreement" : "Service Level Agreement"}
                                            </a>
                                        </span>
                                    )}



                                </label>
                                {errors.terms && <p className="text-red-500 text-sm">{errors.terms}</p>}
                            </div>
                            <div className="flex justify-between items-center">
                                <button type="button" onClick={prevStep} className="text-blue-700 hover:underline">Back</button>
                                <button type="submit" disabled={isSubmitting}
                                    className={`flex items-center gap-2 bg-blue-800 text-white px-5 py-2 rounded-lg ${isSubmitting ? 'opacity-50 cursor-not-allowed' : ''}`}>
                                    {isSubmitting ? (
                                        <>
                                            <svg className="animate-spin h-5 w-5 mr-2 text-white" viewBox="0 0 24 24">
                                                {/* spinner */}
                                            </svg>
                                            Registering...
                                        </>
                                    ) : "Register"}
                                </button>
                            </div>
                        </>
                    )}
                </form>
            </div>
        </section>
    );
}
