'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X } from 'lucide-react';
import { FaArrowLeftLong, FaArrowRightLong } from 'react-icons/fa6';
import countryData from "@/data/countryData";
import { userInquiryAPI } from "@/lib/api";
import Swal from 'sweetalert2';
import { SingleValue } from "react-select";
import { useRouter } from 'next/navigation';
import Image from 'next/image';


const FixedPopup = ({ isOpen, setIsOpen }: { isOpen: boolean; setIsOpen: (open: boolean) => void }) => {



//   const [isOpen, setIsOpen] = useState(false);
  const [step, setStep] = useState(1); // Step tracker

  const router = useRouter();

    const [selectedCountry, setSelectedCountry] = useState(""); // Country Name
    const [selectedCountryCode, setSelectedCountryCode] = useState(""); // Country Code
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState("");


    const handleFocusdrop = () => {
        setIsDropdownOpen(true);
    };

    interface CountryOption {
        label: string;
        value: string;
    }
    
    const handleSelectCountry = (country: SingleValue<CountryOption>) => {
        if (!country) return; // à¤¯à¤¦à¤¿ country null à¤¹à¥à¤† à¤¤à¥‹ return à¤•à¤° à¤¦à¥‡à¤‚à¤—à¥‡
    
        setSelectedCountry(country.label);
        setSelectedCountryCode(country.value);
    
        //  Also update countryName and countryCode state
        setCountryName(country.label);
        setCountryCode(country.value);
    
        setIsDropdownOpen(false);
        setSearchQuery("");
    };
    
    const handleInquiryTypeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { value } = e.target;
    
        setInquiryType((prev) => 
            prev.includes(value) 
                ? prev.filter((item) => item !== value) 
                : [...prev, value]
        );
    };
    
    
    const handleDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setDescription(e.target.value);
    };
    
    

    // Filter countries based on search query
    const filteredCountries = countryData.filter((country) =>
        country.label.toLowerCase().includes(searchQuery.toLowerCase())
    );


//   API Code Start 

    //   PERFECT API CODE START 

    const [name,setName] = useState("");
    const [email,setEmail] = useState("");
    const [countryName,setCountryName] = useState("");
    const [countryCode,setCountryCode] = useState("");
    const [mobile,setMobile] = useState("");
    // const [workType,setWorkType] = useState("");
    // const [budget,setBudget] = useState("");
    const [inquiryType, setInquiryType] = useState<string[]>([]); // Ensure it's an array
    const [description,setDescription] = useState("");


    const [errName,setErrName] = useState("");
    const [errEmail,setErrEmail] = useState("");
    const [errCountryName,setErrCountryName] = useState("");
    const [errMobile,setErrMobile] = useState("");

    // const [response, setResponse] = useState(null);
    const [loading, setLoading] = useState(false);
    
    const Validation=()=>{
        let isValid = true;
        setErrName("");
        setErrEmail("");
        setErrCountryName("");
        setErrMobile("");

        if(name == "")
        {
            isValid = false;
            setErrName("Please Enter Name");
        }
        if(email == "")
        {
            isValid = false;
            setErrEmail("Please Enter Email");
        }
        if(countryName == "")
        {
            isValid = false;
            setErrCountryName("Please Enter Your Country");
        }
        if(mobile == "")
        {
            isValid = false;
            setErrMobile("Please Enter Mobile Number");
        }
        return isValid
    }
    

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        // console.log("Validation result: ", skill); // Debugging
        
        if(Validation())
            {
            setLoading(true);
            const formData = {
                name,
                email,
                countryName,  // Now correctly updated
                countryCode,
                mobile,
                // workType,
                // budget,
                inquiryType,
                description,
            };
    
            // console.log("Submitted Data:", formData);
    
            userInquiryAPI(formData).then((data) => {
                if(data.data.status)
                {
                     // Success popup
                    Swal.fire({
                        title: "Success!",
                        text: "Data sent successfully!",
                        icon: "success",
                        confirmButtonText: "OK"
                    }).then(() => {
                        // window.location.reload(); // This will reload the page
                        window.location.href = "/";
                    });
    
                   
                }
                else{
                    // setResponse(data.data.massage);
                    // Error popup
                    Swal.fire({
                        title: "Error!",
                        text: "Failed to send data!",
                        icon: "error",
                        confirmButtonText: "Try Again"
                    });
                }
                setLoading(false);
            })
        }
    }
    const Name = (e: React.ChangeEvent<HTMLInputElement>) => {
        setName(e.target.value);
    };
    
    const Email = (e: React.ChangeEvent<HTMLInputElement>) => {
        setEmail(e.target.value);
    };
    
    const CountryCode = (e: React.ChangeEvent<HTMLInputElement>) => {
        setCountryCode(e.target.value);
    };
    
    const Mobile = (e: React.ChangeEvent<HTMLInputElement>) => {
        setMobile(e.target.value);
    };
    
    //   PERFECT API CODE END 

  


  return (
    <div>
      {/* Fixed Icon */}
      {/* {!hiddenRoutes.includes('sales-coordinator-career-form') && ( */}
      {/* {!hiddenRoutes.includes(pathname) && ( */}
            <button
                onClick={() => setIsOpen(true)}
                className="fixed bottom-5 w-[50px] h-[50px] right-5 z-40 cursor-pointer bg-[#000] text-white p-4 rounded-full shadow-lg hover:bg-orange-600 transition duration-300"
                aria-label="Generate A Quote"
            >
                <Image src="/images/favicon_icon.png"  className='w-full mt-[-3px]' width={1200} height={600} alt="Fruxinfo favicon" />
                {/* <MessageCircle size={24} /> */}
            </button>
        {/* )} */}

      {/* Popup Modal with Animation */}
        <AnimatePresence>
          {isOpen && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="GetQuat_Custome_Popup fixed inset-0 flex justify-center items-center z-50 bg-black bg-opacity-50">
              <motion.div initial={{ scale: 0, x: "40vw", y: "40vh" }} animate={{ scale: 1, x: 0, y: 0 }} exit={{ scale: 0, x: "40vw", y: "40vh" }} transition={{ duration: 0.5, ease: "easeOut" }} className="bg-white px-3 md:px-6 pt-10 pb-15 rounded-lg shadow-lg w-full md:w-[800px] relative">
                {/* Close Button */}
                <button 
                    onClick={() => {
                        setIsOpen(false);
                        setTimeout(() => {
                            router.refresh();
                        }, 300); // 300ms delay to allow modal to close
                      }} 
                    className="absolute top-3 right-3 text-gray-600 hover:text-gray-900 cursor-pointer">
                  <X size={24} />
                </button>

                {/* Back Button (Now goes back one step at a time) */}
                {step > 1 && (
                  <button onClick={() => setStep(step - 1)} className='absolute top-6 left-6'>
                    <FaArrowLeftLong className="h-[30px] w-[30px]" />
                  </button>
                )}

                <h2 className="text-[25px] mb-4 font-bold text-center text-[#000]">Generate A Quote</h2>
                <form onSubmit={handleSubmit}>
                  {/* Step 1 - First_M1 */}
                  <motion.div className="" initial={{ height: "auto" }} animate={{ height: step === 1 ? "auto" : "0px", overflow: "hidden" }} transition={{ duration: 0.5 }}>
                    <p className="text-[16px] font-bold text-[#000] text-center mt-2">
                      What services would you like to opt?
                    </p>
                    <div className="py-3 w-[250px] mx-auto">
                        {["Remote Developer Hiring", "Mobile Apps", "Web Design", "Digital Marketing", "Other"].map((service, index) => (
                            <div key={index} className="my-2">
                                <label className="checkbox-container">
                                    <input type="checkbox" value={service} onChange={handleInquiryTypeChange} />
                                    <span className="checkbox-text">{service}</span>
                                </label>
                            </div>
                        ))}
                    </div>

                    <div className="flex justify-center">
                        <button
                            className={`group text-[20px] text-[#E77025] cursor-pointer flex items-center gap-2 
                                hover:font-bold transition-all duration-300 ${inquiryType.length === 0 ? "opacity-50 cursor-not-allowed" : ""}`}
                            disabled={inquiryType.length === 0}
                            onClick={(e) => {
                                e.preventDefault(); // Prevent form submission
                                setStep(2);
                            }}
                        >
                            Continue
                            <FaArrowRightLong className="h-[20px] w-[20px] group-hover:translate-x-3 transition-transform duration-300" />
                        </button>
                    </div>
                  </motion.div>

                  {/* Step 3 - Project Description */}
                  <motion.div className="" initial={{ height: "0px", opacity: 0, overflow: "hidden" }} animate={{ height: step === 2 ? "auto" : "0px", opacity: step === 2 ? 1 : 0 }} transition={{ duration: 0.5 }}>
                  <div className="py-3 w-[400px] mx-auto">
                      <label htmlFor="" className='text-[20px] font-bold'>Project Description</label>
                      <textarea 
                          name="description" 
                          id="" 
                          onChange={handleDescriptionChange} 
                          className="input_fild w-full"
                      ></textarea>
                  </div>

                  <div className="flex justify-center">
                      <button
                          className={`group text-[20px] text-[#E77025] cursor-pointer flex items-center gap-2 
                              hover:font-bold transition-all duration-300 ${description.trim() === "" ? "opacity-50 cursor-not-allowed" : ""}`}
                          disabled={description.trim() === ""}
                          onClick={(e) => {
                              e.preventDefault(); // Prevent form submission
                              setStep(3);
                          }}
                      >
                          Continue
                          <FaArrowRightLong className="h-[20px] w-[20px] group-hover:translate-x-3 transition-transform duration-300" />
                      </button>
                  </div>
                  </motion.div>

                  {/* Step 5 - Project Description */}
                  <motion.div className="" initial={{ height: "0px", opacity: 0 }} animate={{ height: step === 3 ? "auto" : "0px", opacity: step === 3 ? 1 : 0 }} transition={{ duration: 0.5 }}>
                    <div className='py-10 px-4 w-full md:w-[550px] mx-auto'>
                        <div className='py-3'>
                            <label htmlFor="" className='label_text mb-0'>Hii I am</label>
                            <input type="text" name="name" onChange={Name} className='input_fild ms-0 md:ms-3 text-[24px]' placeholder='eg. Karshan Zala'  />
                        </div>
                        <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errName}</p>
                        <div className='py-3'>
                            <label htmlFor="" className='label_text mb-0'>Reach me at</label>
                            <input type="text" name="email" onChange={Email} className='input_fild ms-0 md:ms-3 text-[24px]' placeholder='eg. karshan.zala@fruxinfo.com'  />
                        </div>
                        <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errEmail}</p>
                        <div className='py-3 country-dropdown-container'>
                            <label htmlFor="" className='label_text mb-0'>Country</label>

                            <input
                                type="text"
                                name="countryName"
                                className="input_fild ms-0 md:ms-3 text-[24px]"
                                placeholder="eg. India"
                                value={selectedCountry}
                                // onFocus={handleChange}
                                onClick={handleFocusdrop}
                                // onChange={CountryName}
                                onChange={(e) => {
                                    setSelectedCountry(e.target.value);
                                    setSearchQuery(e.target.value);
                                }}
                            />
                            <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errCountryName}</p>

                            {/* Dropdown List */}
                            {isDropdownOpen && (
                                <ul className="dropdown-menu">
                                    {filteredCountries.length > 0 ? (
                                        filteredCountries.map((country, index) => (
                                            <li key={index} onClick={() => handleSelectCountry(country)}>
                                                <Image src={`https://flagcdn.com/w40/${country.code.toLowerCase()}.png`} alt={country.label} width={1200} height={600} style={{ width: 20, marginRight: 10 }} />
                                                {country.label} (+{country.value}) {/* Use 'value' for code */}
                                            </li>
                                        ))
                                    ) : (
                                        <li>No country found</li>
                                    )}
                                </ul>
                            )}
                        </div>
                        <div className='py-3 md:flex'>
                            <label htmlFor="" className='label_text mb-0'>Mobile No.</label>
                            <div>

                                <input
                                    type="text"
                                    name="countryCode"
                                    className="input_fild cuntriw ms-0 md:ms-3 text-[24px] w-[70px]" // Adjust width as needed
                                    placeholder="+ Code"
                                    onChange={CountryCode}
                                    value={selectedCountryCode ? `+${selectedCountryCode}` : ""}
                                    readOnly // Country code is not editable
                                />

                                {/* Actual Mobile Number Input */}
                                <input
                                    type="number"
                                    name="mobile"
                                    onChange={Mobile}
                                    className="input_fild numberw text-[24px] flex-1"
                                    placeholder="Enter Mobile Number"
                                    // value={mobileNumber}
                                    // onChange={(e) => setMobileNumber(e.target.value.replace(/[^0-9]/g, ""))}
                                />
                            </div>
                        </div>
                            <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errMobile}</p>
                        <div className='flex justify-center mt-8'>
                            <div>
                                <button type="submit"  className='Custome_Orange_button submit_btn' disabled={loading}>{loading ? "Sending..." : "Submit"}</button>
                            </div>
                        </div>
                    </div>
                  </motion.div>

                </form>

              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>
    </div>
  );
};

export default FixedPopup;
