"use client";

import { ArrowLeft, Search, MapPin, ChevronDown, Check, X, Loader2, Building2, Filter as FilterIcon } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
import { useCompanies, useIndustriesOptions, useOrgTypeOptions, useSizeOptions } from "@/hooks/useCompanies";
import { useCompanyFiltersStore } from "@/store/companyFilters.store";

export function CompanyListingClient() {
  const { filters, setFilter, resetFilters, removeArrayFilter } = useCompanyFiltersStore();
  const [searchInput, setSearchInput] = useState(filters.keyword);
  const [locationInput, setLocationInput] = useState(filters.locations[0] || "");

  const [expandedIndustry, setExpandedIndustry] = useState(true);
  const [expandedOrgType, setExpandedOrgType] = useState(true);
  const [expandedCompanySize, setExpandedCompanySize] = useState(true);

  // Modal states
  const [isIndustryModalOpen, setIsIndustryModalOpen] = useState(false);
  const [industrySearch, setIndustrySearch] = useState("");
  const [tempSelectedIndustries, setTempSelectedIndustries] = useState<string[]>([]);

  const { data: companiesData, isLoading } = useCompanies();
  const { data: industriesData } = useIndustriesOptions();
  const { data: orgTypesData } = useOrgTypeOptions();
  const { data: sizesData } = useSizeOptions();

  const companies = companiesData?.data || [];
  const total = companiesData?.totalItems || 0;
  const totalPages = companiesData?.totalPages || 1;

  const handleSearch = () => {
    setFilter("keyword", searchInput);
    if (locationInput.trim()) {
      setFilter("locations", [locationInput.trim()]);
    } else {
      setFilter("locations", []);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // Reusable logo component (falls back to letter if no URL)
  const renderLogo = (company: any) => {
    if (company.c_logo && company.c_logo.startsWith('http')) {
      return (
        <div className="relative w-full h-full rounded-lg overflow-hidden border border-gray-100 bg-white">
          <Image src={company.c_logo} alt={company.c_name || 'Company Logo'} fill className="object-contain p-2" />
        </div>
      );
    }
    
    // Fallback logic
    const firstLetter = company.c_name ? company.c_name.charAt(0).toUpperCase() : 'C';
    const bgColors = ['bg-blue-500', 'bg-purple-600', 'bg-rose-500', 'bg-emerald-500', 'bg-amber-500'];
    const colorIndex = (company.c_id || 0) % bgColors.length;
    
    return (
      <div className={`w-full h-full ${bgColors[colorIndex]} rounded-lg text-white flex items-center justify-center font-bold text-2xl`}>
        {firstLetter}
      </div>
    );
  };

  return (
    <div className="bg-[#fcfdfd] min-h-screen font-sans">
      
      {/* Top Banner Section */}
      <div className="relative bg-gradient-to-r from-orange-50/80 via-rose-50/50 to-orange-100/60 pt-10 pb-10 px-4 lg:px-8 border-b border-orange-100/50 overflow-hidden">
         {/* Decorative background image right side */}
         <div className="absolute right-0 top-10 h-full w-[400px] pointer-events-none hidden md:block z-0">
            <div className="absolute inset-0 bg-[url('/images/company.png')] bg-contain bg-right-top bg-no-repeat"></div>
         </div>
         
         <div className="container mx-auto max-w-7xl relative z-10">
            <div className="mb-2">
              <Link href="/" className="inline-flex items-center gap-3 text-gray-900 font-bold text-[28px] hover:text-[#ff6b00] transition-colors leading-none">
                <ArrowLeft className="w-6 h-6" strokeWidth={2.5} />
                All Companies
              </Link>
            </div>
            <p className="text-gray-500 text-[15px] ml-9 font-medium mb-6">{total} companies found</p>
            
            {/* Search Bar inside the banner */}
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-2 flex flex-col md:flex-row items-center gap-2 lg:w-[calc(100%-420px)]">
              
              <div className="flex-1 flex items-center px-4 py-2 border-b md:border-b-0 md:border-r border-gray-100 w-full md:w-auto">
                <Search className="w-5 h-5 text-gray-400 mr-3 flex-shrink-0" />
                <input 
                  type="text" 
                  value={searchInput}
                  onChange={(e) => setSearchInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Enter Company Name" 
                  className="w-full outline-none text-sm text-gray-700 placeholder:text-gray-400"
                />
              </div>

              <div className="flex-1 flex items-center px-4 py-2 w-full md:w-auto">
                <MapPin className="w-5 h-5 text-gray-400 mr-3 flex-shrink-0" />
                <input 
                  type="text" 
                  value={locationInput}
                  onChange={(e) => setLocationInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Enter Location" 
                  className="w-full outline-none text-sm text-gray-700 placeholder:text-gray-400"
                />
              </div>

              <button 
                onClick={handleSearch}
                className="w-full md:w-auto bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-3 rounded-lg text-sm font-bold transition-colors flex-shrink-0"
              >
                Search &rarr;
              </button>
            </div>
         </div>
      </div>

      <div className="container mx-auto max-w-7xl px-4 lg:px-8 pb-12 pt-8">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
           
            {/* LEFT COLUMN: Filters */}
            <div className="lg:col-span-3 hidden lg:block">
               <div className="bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden sticky top-4">
                  
                  <div className="p-5 border-b border-gray-100 flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <FilterIcon className="w-5 h-5 text-gray-600" />
                      <h2 className="font-bold text-gray-900 text-base">Filters</h2>
                    </div>
                    <button onClick={resetFilters} className="text-[12px] font-bold text-[#ff6b00] hover:underline">Clear All</button>
                  </div>

                  <div className="p-5 space-y-6 max-h-[calc(100vh-200px)] overflow-y-auto">
                     
                     {/* Actively Hiring Toggle */}
                     <div className="flex items-center gap-3">
                       <input 
                         type="checkbox"
                         id="isHiring"
                         checked={filters.isHiring}
                         onChange={(e) => setFilter('isHiring', e.target.checked)}
                         className="w-4 h-4 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                       />
                       <label htmlFor="isHiring" className="text-sm font-medium text-gray-700 cursor-pointer">
                         Actively Hiring
                       </label>
                     </div>

                     {/* Industry Filter */}
                     <div className="border-t border-gray-100 pt-5">
                       <button 
                         onClick={() => setExpandedIndustry(!expandedIndustry)}
                         className="flex items-center justify-between w-full mb-3 group"
                       >
                         <h3 className="font-bold text-gray-900 text-[13px] uppercase tracking-wider group-hover:text-[#ff6b00] transition-colors">Industry</h3>
                         <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${expandedIndustry ? 'rotate-180' : ''}`} />
                       </button>
                       {expandedIndustry && (
                         <div className="space-y-3">
                           {industriesData?.data?.slice(0, 5).map((ind: any) => (
                             <div key={ind.id} className="flex items-center gap-3">
                               <input 
                                 type="checkbox"
                                 id={`ind-${ind.id}`}
                                 checked={filters.industries.includes(ind.id.toString())}
                                 onChange={(e) => {
                                   const current = filters.industries;
                                   const val = ind.id.toString();
                                   setFilter('industries', e.target.checked ? [...current, val] : current.filter(id => id !== val));
                                 }}
                                 className="w-4 h-4 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                               />
                               <label htmlFor={`ind-${ind.id}`} className="text-sm text-gray-600 cursor-pointer flex-1 line-clamp-1">{ind.name}</label>
                             </div>
                           ))}
                           {(industriesData?.data?.length || 0) > 5 && (
                             <button 
                               onClick={() => {
                                 setTempSelectedIndustries(filters.industries);
                                 setIndustrySearch("");
                                 setIsIndustryModalOpen(true);
                               }} 
                               className="text-sm font-medium text-[#ff6b00] hover:underline"
                             >
                               View More
                             </button>
                           )}
                         </div>
                       )}
                     </div>

                     {/* Org Type Filter */}
                     <div className="border-t border-gray-100 pt-5">
                       <button 
                         onClick={() => setExpandedOrgType(!expandedOrgType)}
                         className="flex items-center justify-between w-full mb-3 group"
                       >
                         <h3 className="font-bold text-gray-900 text-[13px] uppercase tracking-wider group-hover:text-[#ff6b00] transition-colors">Organization Type</h3>
                         <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${expandedOrgType ? 'rotate-180' : ''}`} />
                       </button>
                       {expandedOrgType && (
                         <div className="space-y-3">
                           {orgTypesData?.data?.map((org: any) => (
                             <div key={org.id} className="flex items-center gap-3">
                               <input 
                                 type="checkbox"
                                 id={`org-${org.id}`}
                                 checked={filters.organizationTypes.includes(org.id.toString())}
                                 onChange={(e) => {
                                   const current = filters.organizationTypes;
                                   const val = org.id.toString();
                                   setFilter('organizationTypes', e.target.checked ? [...current, val] : current.filter(id => id !== val));
                                 }}
                                 className="w-4 h-4 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                               />
                               <label htmlFor={`org-${org.id}`} className="text-sm text-gray-600 cursor-pointer flex-1">{org.label}</label>
                             </div>
                           ))}
                         </div>
                       )}
                     </div>

                     {/* Company Size Filter */}
                     <div className="border-t border-gray-100 pt-5">
                       <button 
                         onClick={() => setExpandedCompanySize(!expandedCompanySize)}
                         className="flex items-center justify-between w-full mb-3 group"
                       >
                         <h3 className="font-bold text-gray-900 text-[13px] uppercase tracking-wider group-hover:text-[#ff6b00] transition-colors">Company Size</h3>
                         <ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${expandedCompanySize ? 'rotate-180' : ''}`} />
                       </button>
                       {expandedCompanySize && (
                         <div className="space-y-3">
                           {sizesData?.data?.map((size: any) => (
                             <div key={size.id} className="flex items-center gap-3">
                               <input 
                                 type="checkbox"
                                 id={`size-${size.id}`}
                                 checked={filters.companySizes.includes(size.id.toString())}
                                 onChange={(e) => {
                                   const current = filters.companySizes;
                                   const val = size.id.toString();
                                   setFilter('companySizes', e.target.checked ? [...current, val] : current.filter(id => id !== val));
                                 }}
                                 className="w-4 h-4 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                               />
                               <label htmlFor={`size-${size.id}`} className="text-sm text-gray-600 cursor-pointer flex-1">{size.label}</label>
                             </div>
                           ))}
                         </div>
                       )}
                     </div>

                  </div>
               </div>
            </div>

           {/* RIGHT COLUMN: Company Grid */}
           <div className="lg:col-span-9 flex flex-col">
              
              {/* Active Filters Section */}
              {(filters.keyword || filters.locations.length > 0 || filters.isHiring || filters.industries.length > 0 || filters.organizationTypes.length > 0 || filters.companySizes.length > 0) && (
                <div className="mb-6 flex flex-wrap items-center gap-2">
                  <span className="text-sm font-medium text-gray-500 mr-2">Active Filters:</span>
                  
                  {filters.keyword && (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gray-100 text-gray-700 text-[13px] font-medium border border-gray-200">
                      Search: {filters.keyword}
                      <button onClick={() => setFilter('keyword', '')} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                    </span>
                  )}

                  {filters.locations.map(loc => (
                    <span key={`loc-${loc}`} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gray-100 text-gray-700 text-[13px] font-medium border border-gray-200">
                      Location: {loc}
                      <button onClick={() => { setLocationInput(""); removeArrayFilter('locations', loc); }} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                    </span>
                  ))}

                  {filters.isHiring && (
                    <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-orange-50 text-[#ff6b00] text-[13px] font-medium border border-orange-100">
                      Actively Hiring
                      <button onClick={() => setFilter('isHiring', false)} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                    </span>
                  )}

                  {filters.industries.map(id => {
                    const name = industriesData?.data?.find((i: any) => i.id.toString() === id)?.name || 'Industry';
                    return (
                      <span key={`ind-${id}`} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gray-100 text-gray-700 text-[13px] font-medium border border-gray-200">
                        {name}
                        <button onClick={() => removeArrayFilter('industries', id)} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                      </span>
                    );
                  })}

                  {filters.organizationTypes.map(id => {
                    const name = orgTypesData?.data?.find((o: any) => o.id.toString() === id)?.label || 'Type';
                    return (
                      <span key={`org-${id}`} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gray-100 text-gray-700 text-[13px] font-medium border border-gray-200">
                        {name}
                        <button onClick={() => removeArrayFilter('organizationTypes', id)} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                      </span>
                    );
                  })}

                  {filters.companySizes.map(id => {
                    const name = sizesData?.data?.find((s: any) => s.id.toString() === id)?.label || 'Size';
                    return (
                      <span key={`size-${id}`} className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gray-100 text-gray-700 text-[13px] font-medium border border-gray-200">
                        Size: {name}
                        <button onClick={() => removeArrayFilter('companySizes', id)} className="hover:text-red-500 transition-colors"><X className="w-3.5 h-3.5" /></button>
                      </span>
                    );
                  })}

                  <button 
                    onClick={() => {
                      resetFilters();
                      setSearchInput("");
                      setLocationInput("");
                    }} 
                    className="ml-2 text-sm text-[#ff6b00] hover:underline font-medium"
                  >
                    Clear All
                  </button>
                </div>
              )}
              {isLoading ? (
                 <div className="flex flex-col items-center justify-center py-20 text-gray-400 gap-4">
                    <Loader2 className="w-10 h-10 animate-spin text-[#ff6b00]" />
                    <p className="font-medium">Loading companies...</p>
                 </div>
              ) : companies.length === 0 ? (
                 <div className="flex flex-col items-center justify-center py-20 text-gray-400 gap-4 border border-dashed border-gray-300 rounded-2xl bg-gray-50/50">
                    <Building2 className="w-16 h-16 text-gray-300" />
                    <p className="font-medium text-gray-500 text-lg">No companies found</p>
                    <button onClick={() => { resetFilters(); setSearchInput(''); setLocationInput(''); }} className="text-[#ff6b00] font-bold hover:underline">Clear Search</button>
                 </div>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
                  {companies.map((company: any) => {
                    const locationParts = [company.city_name, company.state_name, company.country_name].filter(Boolean);
                    const formattedLocation = locationParts.length > 0 ? locationParts.join(', ') : company.c_location || 'Location not specified';
                    const openPositions = Math.max(0, (company.jobPosts || 0) - (company.expiredJobs || 0));
                    
                    return (
                    <div key={company.c_id} className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow relative flex flex-col h-full group">
                       
                       {company.c_featured === 1 && (
                         <span className="absolute top-4 right-4 bg-[#fff4eb] text-[#ff6b00] text-[10px] font-bold px-2.5 py-1 rounded">
                           Featured
                         </span>
                       )}
                       
                       <Link href={`/companies/${company.c_id}`} className="flex items-center gap-4 mb-5 flex-1 group/link">
                         <div className="w-[60px] h-[60px] flex-shrink-0">
                           {renderLogo(company)}
                         </div>
                         <div>
                           <h3 className="font-bold text-gray-900 leading-tight text-[16px] group-hover/link:text-[#ff6b00] transition-colors line-clamp-2 pr-14">
                             {company.c_name}
                           </h3>
                         </div>
                       </Link>

                       <div className="flex flex-col gap-4 mt-auto">
                          <div className="flex items-start gap-2 text-[13px] text-gray-600 font-medium">
                            <MapPin className="w-4 h-4 text-gray-500 flex-shrink-0 mt-0.5" />
                            <span className="line-clamp-2 leading-snug pr-2">{formattedLocation}</span>
                          </div>
                          
                          <div>
                             <Link href={`/companies/${company.c_id}?tab=jobs`} className="inline-flex items-center gap-2 mt-1 hover:opacity-80 transition-opacity">
                               <div className="bg-blue-100/60 text-blue-600 text-[13px] font-bold px-2 py-1 rounded">
                                 {openPositions}
                               </div>
                               <span className="text-gray-700 text-[13px]">Open Positions</span>
                             </Link>
                          </div>
                       </div>
                    </div>
                  )})}
                </div>
              )}

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-between mt-10 py-6 border-t border-gray-200">
                  <span className="text-sm text-gray-500">Page {filters.page} of {totalPages}</span>
                  <div className="flex items-center gap-1.5 text-sm">
                    <button 
                      onClick={() => setFilter('page', Math.max(1, filters.page - 1))}
                      disabled={filters.page === 1}
                      className="flex items-center gap-1 px-2 py-1 text-gray-400 hover:text-gray-700 transition-colors disabled:opacity-50"
                    >
                      Previous
                    </button>
                    <div className="flex gap-1 mx-2">
                      {Array.from({ length: totalPages }).map((_, idx) => {
                        const pageNumber = idx + 1;
                        if (
                          pageNumber === 1 || 
                          pageNumber === totalPages || 
                          (pageNumber >= filters.page - 1 && pageNumber <= filters.page + 1)
                        ) {
                           return (
                             <button
                               key={pageNumber}
                               onClick={() => setFilter('page', pageNumber)}
                               className={`w-8 h-8 rounded-full flex items-center justify-center font-medium transition-colors ${
                                 pageNumber === filters.page
                                   ? 'bg-[#ff6b00] text-white'
                                   : 'text-gray-600 hover:bg-gray-100'
                               }`}
                             >
                               {pageNumber}
                             </button>
                           );
                        } else if (
                          pageNumber === filters.page - 2 || 
                          pageNumber === filters.page + 2
                        ) {
                          return <span key={pageNumber} className="text-gray-400 mt-1">...</span>;
                        }
                        return null;
                      })}
                    </div>
                    <button 
                      onClick={() => setFilter('page', Math.min(totalPages, filters.page + 1))}
                      disabled={filters.page === totalPages}
                      className="flex items-center gap-1 px-2 py-1 text-gray-400 hover:text-gray-700 transition-colors disabled:opacity-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              )}

           </div>

        </div>
      </div>

      {/* Industry Modal */}
      {isIndustryModalOpen && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
          <div className="bg-white rounded-2xl shadow-xl w-full max-w-2xl flex flex-col max-h-[85vh]">
            
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 pb-4 border-b border-gray-100">
              <h2 className="text-xl font-bold text-gray-900">Industry</h2>
              <button 
                onClick={() => setIsIndustryModalOpen(false)}
                className="text-gray-400 hover:text-gray-600 transition-colors"
              >
                <X className="w-6 h-6" />
              </button>
            </div>

            {/* Modal Search */}
            <div className="px-6 py-4">
              <div className="flex items-center gap-2 px-3 py-2.5 border border-gray-200 rounded-lg bg-gray-50 focus-within:bg-white focus-within:border-[#ff6b00] focus-within:ring-1 focus-within:ring-[#ff6b00] transition-all">
                <Search className="w-4 h-4 text-gray-400" />
                <input 
                  type="text"
                  placeholder="Search Industry"
                  value={industrySearch}
                  onChange={(e) => setIndustrySearch(e.target.value)}
                  className="w-full bg-transparent outline-none text-sm text-gray-700 placeholder:text-gray-400"
                />
              </div>
            </div>

            {/* Modal Body (Scrollable Grid) */}
            <div className="px-6 py-2 overflow-y-auto flex-1 custom-scrollbar">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-4">
                {industriesData?.data
                  ?.filter((ind: any) => ind.name.toLowerCase().includes(industrySearch.toLowerCase()))
                  .map((ind: any) => (
                  <div key={ind.id} className="flex items-start gap-3">
                    <input 
                      type="checkbox"
                      id={`modal-ind-${ind.id}`}
                      checked={tempSelectedIndustries.includes(ind.id.toString())}
                      onChange={(e) => {
                        const val = ind.id.toString();
                        setTempSelectedIndustries(prev => 
                          e.target.checked ? [...prev, val] : prev.filter(id => id !== val)
                        );
                      }}
                      className="w-4 h-4 mt-0.5 text-[#ff6b00] rounded border-gray-300 focus:ring-[#ff6b00]"
                    />
                    <label htmlFor={`modal-ind-${ind.id}`} className="text-sm text-gray-600 cursor-pointer flex-1 leading-snug">
                      {ind.name}
                    </label>
                  </div>
                ))}
              </div>
            </div>

            {/* Modal Footer */}
            <div className="p-6 pt-4 border-t border-gray-100 flex justify-end">
              <button 
                onClick={() => {
                  setFilter('industries', tempSelectedIndustries);
                  setIsIndustryModalOpen(false);
                }}
                className="bg-[#ff6b00] hover:bg-[#e66000] text-white px-8 py-2.5 rounded-lg font-medium transition-colors"
              >
                Apply
              </button>
            </div>
            
          </div>
        </div>
      )}
      
    </div>
  );
}
