// components/auth/PostCategoriesForm.tsx - WITH SEARCHABLE DROPDOWN
'use client';

import React, { useEffect, useState, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/hooks/useRedux';
import { ChevronDown, Loader, X, Search } from 'lucide-react';
import { toast } from 'sonner';
import { getAllCategories, updateCategories } from '@/lib/api/client';
import { 
  updatePostCategoriesStart, 
  updatePostCategoriesSuccess, 
  updatePostCategoriesFailure, 
  resetErrorAndMessage 
} from '@/lib/store/slices/userSlice';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

interface Category {
  _id: string;
  mainCategoryName: string;
}

interface PostCategoriesFormProps {
  logoImage?: any;
  storeLinks?: any[];
  pageData?: any;
  categories?: Category[];
}

export function PostCategoriesForm({ logoImage, storeLinks = [], pageData, categories = [] }: PostCategoriesFormProps) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { currentCustomer, loading } = useAppSelector((state) => state.user);
  
  const [getPostCategories, setGetPostCategories] = useState<Category[]>([]);
  const [openPostCategories, setOpenPostCategories] = useState(false);
  const [previewSelectedCategories, setPreviewSelectedCategories] = useState<Category[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [postCategoriesData, setPostCategoriesData] = useState<{ postCategories: string[] }>({
    postCategories: []
  });
  
  const dropdownRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);
  
  // ✅ Get background image from pageData
  const bgImage = pageData?.mainImage ? `${BASE_URL?.replace(/\/$/, "")}/${pageData?.mainImage?.replace(/^\//, "")}` : null;
  const headerLogo = logoImage?.headerLogo ? `${BASE_URL?.replace(/\/$/, "")}/${logoImage?.headerLogo?.replace(/^\//, "")}` : null;

  // Filter categories based on search term and already selected
  const filteredCategories = getPostCategories.filter((category) => {
    const isNotSelected = !postCategoriesData.postCategories.includes(category._id);
    const matchesSearch = category.mainCategoryName.toLowerCase().includes(searchTerm.toLowerCase());
    return isNotSelected && matchesSearch;
  });

  const handleSelectCategory = (category: Category) => {
    if (postCategoriesData.postCategories.length >= 5) {
      toast.info("You can select only 5 categories");
      setOpenPostCategories(false);
      return;
    }
    setPostCategoriesData((prev) => {
      if (!prev.postCategories.includes(category._id)) {
        const updated = [...prev.postCategories, category._id];
        if (updated.length === 5) {
          setOpenPostCategories(false);
        }
        return { ...prev, postCategories: updated };
      }
      return prev;
    });
    setPreviewSelectedCategories((prev) => {
      if (!prev.find((c) => c._id === category._id)) {
        const updatedPreview = [...prev, category];
        return updatedPreview;
      }
      return prev;
    });
    setSearchTerm(''); // Clear search after selection
  };

  const handleRemoveCategory = (categoryId: string) => {
    setPostCategoriesData((prev) => ({
      ...prev,
      postCategories: prev.postCategories.filter((id) => id !== categoryId),
    }));
    setPreviewSelectedCategories((prev) =>
      prev.filter((cat) => cat._id !== categoryId)
    );
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (postCategoriesData.postCategories.length === 0) {
      const message = "At least One Category is required";
      dispatch(updatePostCategoriesFailure(message));
      toast.error(message);
      return;
    }
    dispatch(updatePostCategoriesStart());
    const data = {
      postCategories: postCategoriesData.postCategories,
      email: currentCustomer?.email,
    };
    const result = await updateCategories(data, logoImage?.securityKey);
    if (result.success) { 
      dispatch(updatePostCategoriesSuccess(result.message));
      toast.success("Post Category Added Successfully");
      router.push("/");
    } else {
      dispatch(updatePostCategoriesFailure(result.message));
      toast.error(result.message);
    }
  };

  const fetchPostCategories = async () => {
    const result = await getAllCategories(logoImage?.securityKey);
    if (result.success) {
      setGetPostCategories(result.data || []);
    }
  };

  useEffect(() => {
    fetchPostCategories();
  }, []);

  useEffect(() => {
    if (!currentCustomer) {
      router.push("/login");
    }
  }, [currentCustomer, router]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setOpenPostCategories(false);
        setSearchTerm('');
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  useEffect(() => {
    dispatch(resetErrorAndMessage());
  }, [dispatch]);

  // Focus search input when dropdown opens
  useEffect(() => {
    if (openPostCategories && searchInputRef.current) {
      setTimeout(() => {
        searchInputRef.current?.focus();
      }, 100);
    }
  }, [openPostCategories]);

  const isFormValid = postCategoriesData.postCategories.length > 0;

  const handleDropdownToggle = () => {
    if (postCategoriesData.postCategories.length >= 5) {
      toast.info("You can select only 5 categories");
      setOpenPostCategories(false);
      return;
    }
    setOpenPostCategories((prev) => !prev);
    if (!openPostCategories) {
      setSearchTerm('');
    }
  };

  return (
    <div className="w-full h-screen flex flex-col md:flex-row overflow-hidden ">
      {/* Left side with background image */}
      <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 - Categories 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">
            <div className="flex gap-2 items-center">
              <p className="text-[20px] leading-[30px] font-semibold text-black">Select Categories</p>
              <p className="text-[14px] leading-[24px] font-semibold text-red-500">(maximum 5)</p>
            </div>
            <p className="text-[14px] leading-[24px] font-medium text-[#6D6D6D]">{currentCustomer?.fullName}</p>
          </div>
          <form onSubmit={handleSubmit} className="flex flex-col gap-2 w-full">
            <div ref={dropdownRef} className="flex flex-col w-full relative">
              <button 
                type="button" 
                disabled={loading} 
                onClick={handleDropdownToggle} 
                className="bg-white cursor-pointer flex justify-between w-full items-center border-gray-300 rounded-md py-2 px-3 border-[1px]"
              >
                <p className="text-[12px] leading-[22px] font-medium text-black">
                  {postCategoriesData.postCategories.length === 0 
                    ? "Select Categories" 
                    : `${postCategoriesData.postCategories.length} category selected`}
                </p>
                <ChevronDown className={`w-5 h-5 transition-transform duration-300 ${openPostCategories ? "rotate-180" : ""}`} />
              </button>
              
              {openPostCategories && (
                <div className="absolute w-full z-20 top-full left-0 mt-1 bg-white border-gray-300 rounded-md border-[1px] shadow-lg">
                  {/* Search Input */}
                  <div className="p-2 border-b border-gray-200">
                    <div className="flex items-center gap-2 px-2 py-1 bg-gray-50 rounded-md border border-gray-200">
                      <Search className="w-4 h-4 text-gray-400" />
                      <input
                        ref={searchInputRef}
                        type="text"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        placeholder="Search categories..."
                        className="flex-1 bg-transparent outline-none text-[12px] text-black placeholder:text-gray-400"
                      />
                      {searchTerm && (
                        <button
                          type="button"
                          onClick={() => setSearchTerm('')}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          <X className="w-3 h-3" />
                        </button>
                      )}
                    </div>
                  </div>
                  
                  {/* Categories List */}
                  <div className="max-h-48 overflow-y-auto custom-scrollbar">
                    {filteredCategories.length > 0 ? (
                      filteredCategories.map((category) => (
                        <p 
                          onClick={() => handleSelectCategory(category)} 
                          key={category._id} 
                          className="cursor-pointer transition-colors px-3 py-2 bg-transparent duration-300 hover:bg-[#F7F7F7] text-[12px] leading-[22px] font-medium text-black"
                        >
                          {category.mainCategoryName}
                        </p>
                      ))
                    ) : (
                      <p className="text-[12px] leading-[22px] font-medium text-gray-400 px-3 py-4 text-center">
                        {searchTerm ? `No categories matching "${searchTerm}"` : "No more categories available"}
                      </p>
                    )}
                  </div>
                </div>
              )}
              
              {/* Selected Categories Preview */}
              {previewSelectedCategories?.length > 0 && (
                <div className="w-full my-2">
                  <div className="flex flex-wrap text-black gap-2">
                    {previewSelectedCategories?.map((showCategory) => (
                      <div key={showCategory._id} className="bg-gray-100 flex gap-1 items-center px-2 py-1 rounded-md">
                        <p className="text-[12px] leading-[12px]">{showCategory.mainCategoryName}</p>
                        <button 
                          type="button"
                          onClick={() => handleRemoveCategory(showCategory._id)} 
                          className="w-5 h-5 flex items-center justify-center cursor-pointer"
                        >
                          <X className="w-3 h-3 text-red-400 transition-all hover:scale-105 duration-300 hover:text-red-600" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
            
            <button 
              disabled={loading || !isFormValid} 
              type="submit" 
              className={`text-white rounded-md w-full transition-colors duration-300 h-10 text-[14px] flex items-center justify-center leading-[24px] font-semibold ${
                isFormValid ? "bg-[#0084a5] cursor-pointer hover:bg-[#006d8a]" : "bg-gray-400 cursor-not-allowed"
              } ${loading ? "opacity-50 cursor-not-allowed" : ""}`}
            >
              {loading ? <Loader className="w-5 h-5 text-white animate-spin" /> : "Submit"}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}