"use client";

import MainContext from "@/app/contexts/mainContext";
import { backendUrl, serAxios } from "@/utils/axios";
import Image from "next/image";
import React, { useContext, useEffect, useState } from "react";
import { ChevronDown, Search } from "lucide-react";
import { useCurrency } from "@/app/contexts/currencyContext";

const getAuthPageData = async () => {
  // Fetch data from external API
  try {
    const res = await serAxios.get("/dynamic-ui/page/auth/");
    const data = res.data;
    return data.data;
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
  // Pass data to the page via props
};

const LoginSignup = () => {
  const [isLogin, setIsLogin] = useState(true);
  const { loginUser, registerUser } = useContext(MainContext);
  const [loginPageData, setLoginPageData] = useState(null);
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    confirmPassword: "",
    country: "",
  });
  const [countries, setCountries] = useState([]);
  const [isCountryDropdownOpen, setIsCountryDropdownOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [filteredCountries, setFilteredCountries] = useState([]);
  const { setUserCountry } = useCurrency();

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleCountrySelect = (country) => {
    setFormData((prevData) => ({
      ...prevData,
      country: country,
    }));
    setIsCountryDropdownOpen(false);
    setSearchTerm("");
  };

  const fetchCountries = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('https://countriesnow.space/api/v0.1/countries/');
      const data = await response.json();
      if (!data.error) {
        setCountries(data.data);
        setFilteredCountries(data.data);
      }
    } catch (error) {
      console.error("Error fetching countries:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (isLogin) {
      loginUser(formData);
    } else {
      // If registering, also set the user's country for currency purposes
      if (formData.country) {
        setUserCountry(formData.country);
      }
      registerUser(formData);
    }
  };

  const toggleMode = () => {
    setIsLogin(!isLogin);
    setFormData({ email: "", password: "", confirmPassword: "", country: "" });
    setSearchTerm("");
  };

  useEffect(() => {
    getAuthPageData().then((data) => {
      setLoginPageData(data);
    });
    
    if (!isLogin) {
      fetchCountries();
    }
  }, [isLogin]);

  // Filter countries based on search term
  useEffect(() => {
    if (countries.length > 0) {
      const filtered = countries.filter(country => 
        country.country.toLowerCase().includes(searchTerm.toLowerCase())
      );
      setFilteredCountries(filtered);
    }
  }, [searchTerm, countries]);

  return (
    <div className="flex h-screen bg-gray-100">
      {/* Left section with video */}
      <div className="hidden lg:flex lg:w-[60%] bg-cover bg-center">
        <video
          src={`${
            loginPageData?.bannerVideo?.path
              ? backendUrl + loginPageData?.bannerVideo?.path
              : "/loginvideo.mp4"
          }`}
          className="object-cover w-full h-full"
          autoPlay
          loop
          muted
          playsInline
        >
          <source src="/loginvideo.mp4" type="video/mp4" />
          Your browser does not support the video tag.
        </video>
      </div>

      {/* Right section with login/signup form */}
      <div className="w-full lg:w-1/2 flex items-center justify-center p-8 ">
        <div className="max-w-md w-full space-y-8 bg-white p-7">
          <div className="flex gap-4 items-center justify-center">
            <Image
              src={"/logo1.jpg"}
              height={200}
              width={200}
              alt="logo"
              className="h-16 w-16 text-center "
            />
            <h1 className="text-[#AC8C6B] text-3xl">{`${
              isLogin ? "Login" : "Sign up"
            }`}</h1>
          </div>
          <form className="mt-8 space-y-6" onSubmit={handleSubmit}>
            <div className="rounded-md shadow-sm -space-y-px flex flex-col gap-5">
              <div>
                <label htmlFor="email-address" className="sr-only">
                  Email address
                </label>
                <input
                  id="email-address"
                  name="email"
                  type="email"
                  autoComplete="email"
                  required
                  className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-[#C19A5B] focus:border-[#C19A5B] focus:z-10 sm:text-sm"
                  placeholder="Email address"
                  value={formData.email}
                  onChange={handleInputChange}
                />
              </div>
              <div>
                <label htmlFor="password" className="sr-only">
                  Password
                </label>
                <input
                  id="password"
                  name="password"
                  type="password"
                  autoComplete="current-password"
                  required
                  className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-[#C19A5B] focus:border-[#C19A5B] focus:z-10 sm:text-sm"
                  placeholder="Password"
                  value={formData.password}
                  onChange={handleInputChange}
                />
              </div>
              {!isLogin && (
                <>
                  <div>
                    <label htmlFor="confirm-password" className="sr-only">
                      Confirm Password
                    </label>
                    <input
                      id="confirm-password"
                      name="confirmPassword"
                      type="password"
                      autoComplete="new-password"
                      required
                      className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-[#C19A5B] focus:border-[#C19A5B] focus:z-10 sm:text-sm"
                      placeholder="Confirm Password"
                      value={formData.confirmPassword}
                      onChange={handleInputChange}
                    />
                  </div>
                  <div className="relative">
                    <button
                      type="button"
                      onClick={() => setIsCountryDropdownOpen(!isCountryDropdownOpen)}
                      className="appearance-none rounded-none relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-[#C19A5B] focus:border-[#C19A5B] focus:z-10 sm:text-sm text-left flex justify-between items-center"
                    >
                      {formData.country ? formData.country : "Select your country"}
                      <ChevronDown className={`w-4 h-4 transition-transform ${isCountryDropdownOpen ? 'rotate-180' : ''}`} />
                    </button>
                    
                    {isCountryDropdownOpen && (
                      <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto">
                        <div className="p-2 border-b">
                          <div className="relative">
                            <Search className="absolute left-2 top-2.5 h-4 w-4 text-gray-400" />
                            <input
                              type="text"
                              placeholder="Search countries..."
                              value={searchTerm}
                              onChange={(e) => setSearchTerm(e.target.value)}
                              className="w-full pl-8 pr-4 py-2 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                          </div>
                        </div>
                        
                        {isLoading ? (
                          <div className="p-3 text-center text-gray-500">Loading countries...</div>
                        ) : filteredCountries.length > 0 ? (
                          filteredCountries.map((countryData) => (
                            <button
                              key={countryData.iso2}
                              type="button"
                              className="block w-full px-4 py-2 text-left hover:bg-gray-100 focus:outline-none focus:bg-gray-100"
                              onClick={() => handleCountrySelect(countryData.country)}
                            >
                              {countryData.country}
                            </button>
                          ))
                        ) : (
                          <div className="p-3 text-center text-gray-500">No countries found</div>
                        )}
                      </div>
                    )}
                  </div>
                </>
              )}
            </div>

            <div>
              <button
                type="submit"
                className="group relative w-full flex justify-center py-2 px-7 border border-transparent text-xl text-[300] font-medium  text-white bg-[#C19A5B] hover:bg-[#c49d60] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
              >
                {isLogin ? "Login" : "Sign up"}
              </button>
            </div>
          </form>
          <div className="text-center">
            <button
              onClick={toggleMode}
              className="font-medium text-[#C19A5B] mt-10"
            >
              {isLogin
                ? "Don't have an account? Sign up"
                : "Already have an account? Sign in"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginSignup;
