import React, { useEffect, useState, useCallback } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { 
  mdiMagnify, 
  mdiMapMarker, 
  mdiFilterVariant, 
  mdiStar, 
  mdiShieldCheck,
  mdiChevronRight,
  mdiSortVariant
} from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetch as fetchBusinesses } from '../stores/businesses/businessesSlice';
import { fetch as fetchCategories } from '../stores/categories/categoriesSlice';
import LayoutGuest from '../layouts/Guest';
import SectionMain from '../components/SectionMain';
import Link from 'next/link';
import type { ReactElement } from 'react';

const SearchPage = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { businesses, loading } = useAppSelector((state) => state.businesses);
  const { categories } = useAppSelector((state) => state.categories);
  const [searchQuery, setSearchQuery] = useState('');
  const [locationQuery, setLocationQuery] = useState('');

  const executeSearch = useCallback((q: string, l: string, category?: string) => {
    let queryStr = '?';
    if (q) queryStr += `name=${encodeURIComponent(q)}&`;
    if (l) queryStr += `city=${encodeURIComponent(l)}&`;
    if (category) queryStr += `category=${encodeURIComponent(category)}&`;
    
    dispatch(fetchBusinesses({ query: queryStr }));
  }, [dispatch]);

  useEffect(() => {
    if (router.isReady) {
      const q = router.query.q as string || '';
      const l = router.query.l as string || '';
      const category = router.query.category as string || '';
      
      setSearchQuery(q);
      setLocationQuery(l);
      
      executeSearch(q, l, category);
      dispatch(fetchCategories({ query: '' }));
    }
  }, [dispatch, router.isReady, router.query, executeSearch]);

  const handleSearchClick = () => {
    router.push({
      pathname: '/search',
      query: { q: searchQuery, l: locationQuery },
    });
  };

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

  return (
    <div className="bg-white min-h-screen font-sans selection:bg-emerald-500/30">
      <Head>
        <title>Find Services | Crafted Network™</title>
      </Head>

      {/* Hero Search Area */}
      <section className="bg-slate-900 pt-32 pb-24 relative overflow-hidden">
        <div className="absolute top-0 left-0 w-full h-full opacity-10">
          <div className="absolute -top-1/2 -left-1/4 w-full h-full bg-emerald-500 blur-[150px] rounded-full"></div>
        </div>
        
        <SectionMain className="relative z-10">
          <div className="max-w-5xl mx-auto space-y-12">
            <h1 className="text-4xl md:text-5xl font-black text-white text-center tracking-tight leading-tight">
              What <span className="text-emerald-400">service</span> are you looking for today?
            </h1>
            
            <div className="flex flex-col md:flex-row gap-4 bg-slate-800/50 p-2 rounded-2xl border border-slate-700/50 backdrop-blur-xl shadow-2xl">
              <div className="flex-1 relative group">
                <BaseIcon path={mdiMagnify} size={24} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-emerald-400" />
                <input 
                  type="text" 
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Service, professional or business name" 
                  className="w-full bg-transparent border-none focus:ring-0 py-3 pl-12 pr-4 text-white placeholder-slate-500"
                />
              </div>
              <div className="w-px bg-slate-700 hidden md:block"></div>
              <div className="flex-1 relative group">
                <BaseIcon path={mdiMapMarker} size={24} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-emerald-400" />
                <input 
                  type="text" 
                  value={locationQuery}
                  onChange={(e) => setLocationQuery(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="City or Zip code" 
                  className="w-full bg-transparent border-none focus:ring-0 py-3 pl-12 pr-4 text-white placeholder-slate-500"
                />
              </div>
              <button 
                onClick={handleSearchClick}
                className="bg-emerald-500 hover:bg-emerald-400 text-slate-900 font-black px-10 py-4 rounded-xl transition-all shadow-lg shadow-emerald-500/20 active:scale-95"
              >
                Search
              </button>
            </div>
          </div>
        </SectionMain>
      </section>

      {/* Main Content */}
      <SectionMain className="py-16">
        <div className="flex flex-col lg:flex-row gap-12">
          {/* Filters Sidebar */}
          <aside className="w-full lg:w-64 space-y-8">
            <div className="flex items-center justify-between lg:mb-8">
              <h3 className="text-xl font-black text-slate-900 flex items-center">
                <BaseIcon path={mdiFilterVariant} size={20} className="mr-2" />
                Filters
              </h3>
              <button 
                onClick={() => {
                  setSearchQuery('');
                  setLocationQuery('');
                  router.push('/search');
                }}
                className="text-sm font-bold text-emerald-600 hover:text-emerald-500"
              >
                Reset
              </button>
            </div>

            <div className="space-y-6">
              <div className="space-y-4">
                <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest">Categories</h4>
                <div className="space-y-2">
                  {categories && categories.slice(0, 8).map((cat: any) => (
                    <Link 
                      key={cat.id} 
                      href={`/search?category=${cat.id}`}
                      className="flex items-center group cursor-pointer"
                    >
                      <input 
                        type="checkbox" 
                        checked={router.query.category === cat.id}
                        readOnly
                        className="w-5 h-5 rounded-md border-slate-200 text-emerald-500 focus:ring-emerald-500 transition-all cursor-pointer" 
                      />
                      <span className="ml-3 text-sm font-medium text-slate-600 group-hover:text-emerald-600 transition-colors">{cat.name}</span>
                    </Link>
                  ))}
                </div>
              </div>

              <div className="space-y-4 pt-6 border-t border-slate-100">
                <h4 className="text-xs font-bold text-slate-400 uppercase tracking-widest">Trust Score</h4>
                <div className="flex items-center justify-between text-xs font-bold text-slate-400">
                  <span>Any</span>
                  <span>80+</span>
                  <span>95+</span>
                </div>
                <input type="range" min="0" max="100" className="w-full h-2 bg-slate-100 rounded-lg appearance-none cursor-pointer accent-emerald-500" />
              </div>
            </div>
          </aside>

          {/* Results Area */}
          <div className="flex-1 space-y-12">
            <div className="flex items-center justify-between border-b border-slate-100 pb-6">
              <div className="text-slate-500 font-medium">
                {loading ? (
                  <span>Searching professionals...</span>
                ) : (
                  <>Found <span className="text-slate-900 font-black">{businesses ? businesses.length : 0} verified</span> professionals</>
                )}
              </div>
              <div className="flex items-center text-sm font-bold text-slate-400">
                <BaseIcon path={mdiSortVariant} size={16} className="mr-2" />
                Sort by: <span className="text-slate-900 cursor-pointer hover:text-emerald-500 transition-colors ml-1">Reliability Score</span>
              </div>
            </div>

            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8 opacity-50">
                {[1, 2, 3, 4].map((i) => (
                  <div key={i} className="h-80 bg-slate-100 rounded-[2.5rem] animate-pulse"></div>
                ))}
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                {businesses && businesses.length > 0 ? (
                  businesses.map((biz: any) => (
                    <Link key={biz.id} href={`/public/businesses-details?id=${biz.id}`} className="group bg-white rounded-[2.5rem] border border-slate-100 hover:border-emerald-100 hover:shadow-2xl hover:shadow-emerald-500/10 transition-all overflow-hidden flex flex-col">
                      <div className="h-48 bg-slate-100 relative overflow-hidden">
                        {biz.business_photos?.[0]?.photo_url ? (
                          <img src={biz.business_photos[0].photo_url} alt={biz.name} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                        ) : (
                          <div className="w-full h-full flex items-center justify-center text-slate-300">
                            <BaseIcon path={mdiShieldCheck} size={48} />
                          </div>
                        )}
                        <div className="absolute top-4 right-4 bg-white/90 backdrop-blur px-3 py-1 rounded-full text-xs font-black text-emerald-600 flex items-center shadow-sm">
                          <BaseIcon path={mdiStar} size={16} className="mr-1" />
                          {biz.rating || '4.9'}
                        </div>
                      </div>
                      <div className="p-8 flex-1 flex flex-col justify-between">
                        <div>
                          <div className="flex items-center justify-between mb-2">
                            <h3 className="text-xl font-black text-slate-900 group-hover:text-emerald-600 transition-colors line-clamp-1">{biz.name}</h3>
                            {biz.is_active && (
                              <BaseIcon path={mdiShieldCheck} size={20} className="text-emerald-500" />
                            )}
                          </div>
                          <div className="flex items-center text-slate-400 text-sm font-bold mb-4">
                            <BaseIcon path={mdiMapMarker} size={16} className="mr-1" />
                            {biz.city || biz.locations?.[0]?.city || 'Verified Professional'}
                          </div>
                        </div>
                        <div className="pt-6 border-t border-slate-50 flex items-center justify-between">
                          <span className="text-xs font-black text-emerald-500 uppercase tracking-widest">Top Professional</span>
                          <div className="w-10 h-10 rounded-xl bg-slate-50 flex items-center justify-center text-slate-300 group-hover:bg-emerald-500 group-hover:text-white transition-all">
                            <BaseIcon path={mdiChevronRight} size={20} />
                          </div>
                        </div>
                      </div>
                    </Link>
                  ))
                ) : (
                  <div className="col-span-full py-24 text-center">
                    <div className="w-20 h-20 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-6 text-slate-300">
                      <BaseIcon path={mdiMagnify} size={40} />
                    </div>
                    <h3 className="text-2xl font-black text-slate-900 mb-2">No results found</h3>
                    <p className="text-slate-500">Try adjusting your filters or searching for something else.</p>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </SectionMain>
    </div>
  );
};

SearchPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};

export default SearchPage;