"use client";

import React, { useRef, useState } from 'react'
import countryData from "@/data/countryData";
// import axios from "axios";
import Swal from 'sweetalert2';

import { userContactUsAPI } from "@/lib/api";
import Image from 'next/image';
const ContactFrom = () => {

    const formRef = useRef<HTMLFormElement>(null);

  const [isShrunk, setIsShrunk] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [hideText, setHideText] = useState(false);
  const [showButton, setShowButton] = useState(false);

  const handleFocus = () => {
    if (!isShrunk) {
      setIsShrunk(true);
      setIsExpanded(true);
      setHideText(true);
      setShowButton(true);
    }
  };

  const handleReset = () => {
    setIsShrunk(false);
    setIsExpanded(false);
    setHideText(false);
    setShowButton(false);
  };

    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: CountryOption) => {
        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]
          );
      };

    // 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 [companyName,setCompanyName] = useState("");
    // const [budget,setBudget] = useState("");
    const [inquiryType, setInquiryType] = useState<string[]>([]);
    const [message,setMessage] = useState("");

    const [errName,setErrName] = useState("");
    const [errEmail,setErrEmail] = useState("");
    const [errCountryName,setErrCountryName] = useState("");
    // const [errCountryCode,setErrCountryCode] = useState("");
    const [errMobile,setErrMobile] = useState("");
    const [errCompanyName,setErrCompanyName] = useState("");
    // const [errBudget,setErrBudget] = useState("");
    const [errInquiryType,setErrInquiryType] = useState("");
    const [errMessage,setErrMessage] = useState("");
    // const [errIncreate,setIncreate] = useState("");

    // const [response, setResponse] = useState(null);
    const [loading, setLoading] = useState(false);
    
    const Validation=()=>{
        let isValid = true;
        setErrName("");
        setErrEmail("");
        setErrCountryName("");
        // setErrCountryCode("");
        setErrMobile("");
        setErrCompanyName("");
        // setErrBudget("");
        setErrInquiryType("");
        setErrMessage("");
        // setIncreate(""); 

        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(countryCode == "")
        // {
        //     isValid = false;
        //     setErrCountryCode("Please Enter Country Code");
        // }
        if(mobile == "")
        {
            isValid = false;
            setErrMobile("Please Enter Mobile Number");
        }
        if(companyName == "")
        {
            isValid = false;
            setErrCompanyName("Please Enter Company Name");
        }
        // if(budget == "")
        // {
        //     isValid = false;
        //     setErrBudget("Please Enter Your Budget");
        // }
        if (inquiryType.length === 0) {
            isValid = false;
            setErrInquiryType("Please select at least one inquiry type");
        }
        if(message == "")
        {
            isValid = false;
            setErrMessage("Please Enter Discription");
        }
        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,
                companyName,
                // budget,
                inquiryType,
                message,
            };
    
            // console.log("Submitted Data:", formData);
    
            userContactUsAPI(formData).then((data) => {
                if(data.data.status)
                {
                    // setResponse(data.data.massage);
                    // Success popup
                    Swal.fire({
                        title: "Success!",
                        text: data.data.message || "Thanks for contacting us! Our team will reach out to you very soon.",
                        icon: "success",
                        confirmButtonText: "OK"
                    }).then(() => {
                        formRef.current?.reset();
                    });
                }
                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);
    };
    
    const CompanyName = (e: React.ChangeEvent<HTMLInputElement>) => {
        setCompanyName(e.target.value);
    };
    
    // const Budget = (e: React.ChangeEvent<HTMLInputElement>) => {
    //     setBudget(e.target.value);
    // };
    
    const Message = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setMessage(e.target.value);
    };
    
    //   PERFECT API CODE END 



  return (
    <div className='ContactFormPage py-20'>
      <div className='max-w-[1200px] mx-auto overflow-hidden px-3'>
        <div className='mb-10'>
            <div>
                <svg height="20" width="30" className={`backAnima ${showButton ? "show-btn" : ""}`} onClick={handleReset} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.2 288 416 288c17.7 0 32-14.3 32-32s-14.3-32-32-32l-306.7 0L214.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg>
            </div>
            <h1 className={`LetsTalk ${hideText ? "hide-text" : ""}`}>Letâ€™s Talk!</h1>
        </div>
        <div className='grid gap-4 sm:grid-cols-12'>
            <div className='sm:col-span-7'>
                <div className={`Custome_form_animation ${isShrunk ? "shrinked" : ""} ${isExpanded ? "expanded" : ""}`}>
                    <form action="" ref={formRef} onSubmit={handleSubmit}>
                        <div className='py-3'>
                            <label htmlFor="" className='label_text mb-0'>Hii I am</label>
                            <input type="text" name="name" className='input_fild ms-0 md:ms-3 text-[24px]' onChange={Name} placeholder='eg. Karshan Zala' onFocus={handleFocus} />
                            <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errName}</p>
                        </div>
                        <div className='py-3'>
                            <label htmlFor="" className='label_text mb-0'>Reach me at</label>
                            <input type="email" name="email" className='input_fild ms-0 md:ms-3 text-[24px]' onChange={Email} placeholder='eg. online@fruxinfo.com' onFocus={handleFocus} />
                        </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" className='input_fild ms-0 md:ms-3 text-[24px]' placeholder='eg. India' onFocus={handleFocus} /> */}
                            <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} style={{ width: 20, marginRight: 10 }} width={1200} height={600} />
                                                {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>
                            {/* <input type="text" className='input_fild ms-0 md:ms-3 text-[24px]' placeholder='98984 12890' /> */}
                        </div>
                            <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errMobile}</p>
                        <div className='py-3'>
                            <label htmlFor="" className='label_text mb-0'>Company Name</label>
                            <input type="text" className='input_fild ms-0 md:ms-3 text-[24px]' onChange={CompanyName} placeholder='Fruxinfo' />
                        </div>
                        <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errCompanyName}</p>
                        <div className='flex flex-wrap gap-4 py-3'>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="UI - UX" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">UI - UX</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Mobile Apps" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Mobile Apps</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Web Design" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Web Design</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Digital Marketing" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Digital Marketing</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Branding" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Branding</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Webflow" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Webflow</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Career" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Career</span>
                                </label>
                            </div>
                            <div>
                                <label className="checkbox-container">
                                    <input type="checkbox" value="Other" onChange={handleInquiryTypeChange} id="customCheck" />
                                    <span className="checkbox-text">Other</span>
                                </label>
                            </div>
                        </div>
                        <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errInquiryType}</p>
                        {/* <div className='py-3'>
                            <label htmlFor="" className='label_text'>Budget in USD</label>
                            <div className='flex flex-wrap gap-4 py-3'>
                                <div>
                                    <label className="checkbox-container">
                                        <input type="radio" name="budget" value="3k - 5k" onChange={Budget} id="customCheck" />
                                        <span className="checkbox-text">3k - 5k</span>
                                    </label>
                                </div>
                                <div>
                                    <label className="checkbox-container">
                                        <input type="radio" name="budget" value="5k - 10k" onChange={Budget} id="customCheck" />
                                        <span className="checkbox-text">5k - 10k</span>
                                    </label>
                                </div>
                                <div>
                                    <label className="checkbox-container">
                                        <input type="radio" name="budget" value="> 10k" onChange={Budget} id="customCheck" />
                                        <span className="checkbox-text"> &gt 10k</span>
                                    </label>
                                </div>
                            </div>
                            <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errBudget}</p>
                        </div> */}
                        <div className='py-3'>
                            <label htmlFor="" className='label_text'>Message</label>
                            <textarea name="message" onChange={Message} className='input_fild text-[24px] w-full' id=""></textarea>
                        </div>
                        <p className='w-full ml-44 mt-2 text-red-700 text-sm'>{errMessage}</p>

                        <div className='flex mt-8'>
                            <div>
                                <button type="submit"  className='Custome_Orange_button submit_btn' disabled={loading}>{loading ? "Sending..." : "Submit"}</button>
                            </div>
                            {/* {response && <p>{response}</p>} */}
                        </div>
                        
                    </form>
                </div>
            </div>
            <div className='sm:col-span-5'>
                <div>
                    <Image src="/images/greate_idea_img.webp" className='w-full mt-10 md:mt-0' alt="Have a great project idea? Discuss with Fruxinfo" width={1200} height={600} />
                    <div className='text-center md:text-end mt-20'>
                        <h4 className='text-[#E77025] text-[22px] py-2'><a href="mailto:karshan.zala@fruxinfo.com">karshan.zala@fruxinfo.com</a></h4>
                        <h4 className='text-[18px] py-2'><span className='text-[#999999] me-4'>IND:</span><a href="tel:+919898412890">+91 98984 12890</a></h4>
                        <h4 className='text-[18px] py-2'><span className='text-[#999999] me-4'>USA:</span><a href="tel:+17322892009">+1(732) 289-2009</a></h4>
                    </div>
                </div>
            </div>
        </div>
      </div>
    </div>
  );
}

export default ContactFrom
