// components/auth/SelectUserNameForm.tsx
'use client';

import React, { useEffect, useState } from 'react';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import Link from 'next/link';
import { BadgeInfo, Loader, Check } from 'lucide-react';
import { getGeneratedUserNames, checkUserNameExits, updateUserName } from '@/lib/api/client';
import { addUserNameFailure, addUserNameStart, addUserNameSuccess, resetErrorAndMessage } from '@/lib/store/slices/userSlice';
import { toast } from 'sonner';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface SelectUserNameFormProps {
  logoImage?: any;
  storeLinks?: any[];
  pageData?: any;  // ✅ Add pageData prop
}

export function SelectUserNameForm({ logoImage, storeLinks = [], pageData }: SelectUserNameFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { currentCustomer, loading } = useAppSelector((state) => state.user);
  
  const [userNames, setUserNames] = useState<string[]>([]);
  const [inputUserName, setInputUserName] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [error, setError] = useState(false);
  const [isChecking, setIsChecking] = useState(false);
  
  // ✅ Get background image from pageData - exactly like old project
  const bgImage = pageData?.mainImage ? `${BASE_URL?.replace(/\/$/, "")}/${pageData?.mainImage?.replace(/^\//, "")}` : null;
  const headerLogo = logoImage?.headerLogo ? `${BASE_URL?.replace(/\/$/, "")}/${logoImage?.headerLogo?.replace(/^\//, "")}` : null;

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);
  
  useEffect(() => {
    if (!currentCustomer) {
      router.push("/login");
    }
  }, [currentCustomer, router]);

  const fetchUserNames = async () => {
    if (!currentCustomer?.fullName || !currentCustomer?.email) return;
    
    const response = await getGeneratedUserNames(
      currentCustomer.fullName, 
      currentCustomer.email, 
      logoImage?.securityKey
    );
    
    if (response?.data?.length) {
      setUserNames(response.data);
      setInputUserName(response.data[0]);
    }
  };

  useEffect(() => {
    fetchUserNames();
  }, [currentCustomer?.fullName, currentCustomer?.email]);

  // Debounced username check
  useEffect(() => {
    if (!inputUserName) {
      setError(false);
      setErrorMessage("");
      return;
    }
    
    const handler = setTimeout(async () => {
      setIsChecking(true);
      const response = await checkUserNameExits(inputUserName, logoImage?.securityKey);
      setIsChecking(false);
      
      if (response.success) {
        setError(false);
        setErrorMessage(response.message || "Username is available");
      } else {
        setError(true);
        setErrorMessage(response.message || "Username already taken");
      }
    }, 800);
    
    return () => clearTimeout(handler);
  }, [inputUserName]);

  const inputChangeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    setInputUserName(value);
    setError(false);
    setErrorMessage("");
  };

  const submitForm = async (event: React.FormEvent) => {
    event.preventDefault();
    
    if (inputUserName.length === 0) {
      const message = "Username is required";
      dispatch(addUserNameFailure(message));
      toast.error(message);
      return;
    }
    
    if (error) {
      toast.error("Username already taken");
      return;
    }
    
    dispatch(addUserNameStart());
    const result = await updateUserName(
      currentCustomer?.email, 
      inputUserName, 
      logoImage?.securityKey
    );
    
    if (result.success) {
      dispatch(addUserNameSuccess(result.message));
      toast.success(result.message);
      router.push("/post-categories");
    } else {
      dispatch(addUserNameFailure(result.message));
      toast.error(result.message);
    }
  };

  const isFormValid = inputUserName && !error && !isChecking;

  return (
    <div className="w-full h-screen flex flex-col md:flex-row overflow-hidden">
      {/* ✅ Left side with background image - exactly like old project */}
      <div 
        className="w-full md:block hidden md:w-1/2 h-full bg-cover bg-center relative" 
        style={{ backgroundImage: `url(${bgImage})` }}
      >
        <Link href="/" className="flex justify-center items-center mx-auto w-24 mt-8">
          {headerLogo && (
            <Image width={500} height={500} priority quality={80} src={headerLogo} alt="Logo" className="w-full" />
          )}
        </Link>
        <div className="flex items-end w-full px-10 absolute bottom-7">
          <div className="flex justify-between items-center w-full">
            <p className="text-[14px] leading-[24px] text-white font-semibold">{logoImage?.copyright}</p>
            <div className="flex gap-2 items-center">
              {storeLinks?.map((store: any) => (
                <Link href={store?.socialLink} key={store?._id} className="w-28 cursor-pointer">
                  <Image width={500} height={500} priority quality={80} src={`${BASE_URL}/${store?.socialIcon}`} alt={store?.socialTitle || "Logo"} className="w-full rounded-sm" />
                </Link>
              ))}
            </div>
          </div>
        </div>
      </div>
      
      {/* Right side - Username Form */}
      <div className="w-full md:w-1/2 justify-center items-center h-full flex flex-col gap-2 bg-[#F5F5F5] sm:px-0 md:px-5 px-5">
        <div className="sm:w-sm md:w-md w-full mx-auto">
          <Link href="/" className="md:hidden flex justify-center">
            {headerLogo && (
              <Image width={500} height={500} priority quality={80} src={headerLogo} alt="Logo" className="w-20" />
            )}
          </Link>
          <div className="w-full flex flex-col">
            <p className="text-[20px] leading-[30px] font-semibold text-black">
              Select Your Username <span className="font-semibold text-[#0084a5]">{currentCustomer?.fullName}</span>
            </p>
            <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">This will be your unique identity</p>
            <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">
              People can mention you using <span className="font-semibold text-[#0084a5]">@username</span>
            </p>
          </div>
          <form onSubmit={submitForm} className="flex flex-col w-full gap-1">
            <div className="flex flex-col w-full gap-0.5 my-1">
              <div className="flex items-center justify-between">
                <p className="text-[12px] text-[#333333] leading-[22px] font-medium">User Name</p>
                {errorMessage && (
                  <p className={`text-[11px] leading-[20px] font-medium ${error ? "text-red-500" : "text-green-600"}`}>
                    {errorMessage}
                  </p>
                )}
              </div>
              <div className="flex items-center border-[1px] border-gray-300 bg-white text-black rounded-md px-3 py-[1px] transition-all duration-300 ease-in-out focus-within:border-[#0084a5] focus-within:shadow-[0_0_8px_0_rgba(0,132,165,0.3)]">
                <input
                  onChange={inputChangeHandler}
                  value={inputUserName}
                  type="text"
                  placeholder="@username123"
                  className="w-full bg-white text-[12px] leading-[22px] placeholder:text-[12px] outline-none"
                  disabled={loading}
                />
                {errorMessage && (
                  <div className={`w-4 h-4 flex items-center justify-center rounded-full p-[1px] shadow-md ${error ? "bg-red-500" : "bg-green-600"}`}>
                    {error ? (
                      <BadgeInfo className="w-3 h-3 text-white" />
                    ) : (
                      <Check className="w-3 h-3 text-white" />
                    )}
                  </div>
                )}
              </div>
            </div>
            
            {/* Suggested Usernames */}
            {userNames?.length > 1 && (
              <div className="flex flex-wrap w-full gap-x-2">
                {userNames?.slice(1)?.map((userName, index) => (
                  <p
                    key={index}
                    className="cursor-pointer text-[14px] leading-[24px] font-semibold text-[#0084a5]"
                    onClick={() => setInputUserName(userName)}
                  >
                    {userName}{index !== userNames.length - 2 && ","}
                  </p>
                ))}
              </div>
            )}
            
            <button
              disabled={loading || !isFormValid}
              type="submit"
              className={`mt-1 text-white rounded-md w-full transition-colors duration-300 h-8 text-[14px] flex items-center justify-center leading-[24px] font-semibold ${
                isFormValid ? "bg-[#0084a5] cursor-pointer" : "bg-gray-600 cursor-not-allowed"
              } ${loading ? "opacity-50 cursor-not-allowed" : null}`}
            >
              {loading ? <Loader className="w-6 h-6 text-white animate-spin" /> : "Next"}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}