"use client";

import { Suspense, useState, useEffect } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Search, Briefcase, MapPin, Building, GraduationCap } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/services/api";
import { useJobFiltersStore } from "@/store/jobFilters.store";

function JobSearchContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  
  const initialKeyword = searchParams.get("keyword") || "Jobs By City";
  
  const [activeTab, setActiveTab] = useState(initialKeyword);
  const [searchQuery, setSearchQuery] = useState("");
  const { setFilter, resetFilters } = useJobFiltersStore();

  const tabs = [
    { id: "Jobs By Types", label: "By Types", icon: Briefcase, endpoint: "/job_type", dataKey: "job_type_name", subtitle: "Select a job type to discover relevant opportunities" },
    { id: "Jobs By City", label: "By City", icon: MapPin, endpoint: "/city/featured", dataKey: "city_name", subtitle: "Tap a city to see openings near you" },
    { id: "Jobs By Industry", label: "By Industry", icon: Building, endpoint: "/industries", dataKey: "industry_name", subtitle: "Find roles matched to your skillset" },
    { id: "Jobs By Education", label: "By Education", icon: GraduationCap, endpoint: "/education_levels", dataKey: "education_level_name", subtitle: "Discover roles that align with your education" },
  ];

  const currentTab = tabs.find(t => t.id === activeTab) || tabs[1];

  const { data: listData, isLoading } = useQuery({
    queryKey: ["jobSearchData", currentTab.endpoint],
    queryFn: async () => {
      const res = await api.get(currentTab.endpoint);
      return res.data?.data || res.data || [];
    }
  });

  const handleTabClick = (tabId: string) => {
    setActiveTab(tabId);
    router.push(`/job-search?keyword=${tabId.replace(/ /g, "+")}`);
  };

  const getLabel = (item: any) => {
    if (activeTab === "Jobs By City") return item.city_name || item.name;
    if (activeTab === "Jobs By Industry") return item.industry_name || item.name;
    if (activeTab === "Jobs By Types") return item.job_type_name || item.type_name || item.name;
    if (activeTab === "Jobs By Education") return item.education_level_name || item.education_name || item.name || item.level_name;
    return item.name || item.title || "Unknown";
  };

  const filteredData = listData?.filter((item: any) => {
    if (!searchQuery) return true;
    const label = getLabel(item).toLowerCase();
    return label.includes(searchQuery.toLowerCase());
  }) || [];

  const handleItemClick = (item: any) => {
    const label = getLabel(item);
    resetFilters();
    
    const safeLabel = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)+/g, '');
    let slug = "";
    
    if (activeTab === "Jobs By City") {
      slug = `jobs-in-${safeLabel}`;
    } else if (activeTab === "Jobs By Industry") {
      slug = `jobs-by-industry-${safeLabel}`;
    } else if (activeTab === "Jobs By Education") {
      slug = `jobs-by-education-${safeLabel}`;
    } else if (activeTab === "Jobs By Types") {
      slug = `jobs-by-type-${safeLabel}`;
    }
    
    if (slug) {
      router.push(`/jobs/${slug}`);
    } else {
      router.push("/jobs");
    }
  };

  return (
    <div className="min-h-screen bg-[#f8f9fa] pt-4 pb-12">
      <div className="max-w-[1000px] mx-auto px-6">
        
        {/* Header Section */}
        <div className="text-center mb-3">
          <h1 className="text-[40px] md:text-[46px] font-bold text-gray-900 leading-tight mb-4 tracking-tight">
            Find your next job,<br />
            <span className="text-[#ff6b00]">wherever you want it.</span>
          </h1>
          <p className="text-gray-500 text-[15px] max-w-2xl mx-auto leading-relaxed">
            Browse thousands of open roles by city, company or department — or just start typing and we'll narrow it down instantly.
          </p>
        </div>

        {/* Search Bar */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-2 flex items-center mb-10 max-w-3xl mx-auto">
          <div className="pl-4 pr-2 text-gray-400">
            <Search className="w-5 h-5" />
          </div>
          <input 
            type="text" 
            placeholder="Search for job type, city, industry or education level"
            className="flex-1 py-3 px-2 outline-none text-[15px] text-gray-700 placeholder-gray-400"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        {/* Tabs Section */}
        <div className="relative mb-12 max-w-3xl mx-auto">
          {/* Dashed line background */}
          <div className="absolute top-1/2 left-0 right-0 h-[1px] border-t-2 border-dashed border-gray-200 -z-10 -translate-y-1/2"></div>
          
          <div className="flex justify-between items-center bg-transparent">
            {tabs.map((tab) => {
              const isActive = activeTab === tab.id;
              const Icon = tab.icon;
              return (
                <div key={tab.id} className="flex flex-col items-center bg-[#f8f9fa] px-4 cursor-pointer group" onClick={() => handleTabClick(tab.id)}>
                  <div className={`w-[60px] h-[60px] rounded-full flex items-center justify-center transition-colors shadow-sm mb-4 ${isActive ? 'bg-[#ff6b00] text-white ring-4 ring-orange-50' : 'bg-white text-gray-500 group-hover:bg-gray-50 border border-gray-100'}`}>
                    <Icon className={`w-6 h-6 ${isActive ? 'text-white' : 'text-gray-500'}`} strokeWidth={isActive ? 2 : 1.5} />
                  </div>
                  <span className={`text-[13px] font-semibold transition-colors ${isActive ? 'text-gray-900' : 'text-gray-500 group-hover:text-gray-700'}`}>
                    {tab.label}
                  </span>
                </div>
              )
            })}
          </div>
        </div>

        {/* Content Section */}
        <div className="mb-6 max-w-4xl mx-auto">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-end mb-5 gap-2">
            <h2 className="text-xl font-bold text-gray-900">{currentTab.label.replace('By', 'Jobs by')}</h2>
            <span className="text-[13px] font-medium text-gray-500">{currentTab.subtitle}</span>
          </div>

          {isLoading ? (
            <div className="flex justify-center py-20">
              <div className="w-8 h-8 border-4 border-[#ff6b00] border-t-transparent rounded-full animate-spin"></div>
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-3">
              {filteredData.length > 0 ? filteredData.map((item: any, i: number) => (
                <button 
                  key={i} 
                  onClick={() => handleItemClick(item)}
                  className="bg-white hover:border-[#ff6b00] hover:text-[#ff6b00] border border-gray-100 shadow-sm py-3.5 px-4 rounded-[12px] text-[13px] font-medium text-gray-600 text-center transition-all hover:shadow-md truncate"
                >
                  {getLabel(item)}
                </button>
              )) : (
                <div className="col-span-full text-center py-10 text-gray-500 text-sm">
                  No data found for {currentTab.label.toLowerCase()}
                </div>
              )}
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

export default function JobSearchPage() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-[#f8f9fa] flex items-center justify-center"><div className="w-8 h-8 border-4 border-[#ff6b00] border-t-transparent rounded-full animate-spin"></div></div>}>
      <JobSearchContent />
    </Suspense>
  );
}
