import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import LayoutGuest from '../../layouts/Guest';
import WebHeader from '../../components/WebHeader';
import WebFooter from '../../components/WebFooter';
import axios from 'axios';
import { useAppSelector } from '../../stores/hooks';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import { mdiArrowRight, mdiMagnify } from '@mdi/js';
import BaseIcon from '../../components/BaseIcon';

export default function ServicesPage() {
  const projectName = useAppSelector((state) => state.style.projectName) || 'FreelanceFusion';
  const [services, setServices] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [servicesRes, categoriesRes] = await Promise.all([
          axios.get('/service_listings'),
          axios.get('/service_categories')
        ]);
        setServices(servicesRes.data.rows || []);
        setCategories(categoriesRes.data.rows || []);
      } catch (err) {
        console.error('Failed to fetch public services:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const filteredServices = services.filter(service => 
    service.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    service.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Head>
        <title>Student Services | {projectName}</title>
        <meta name="description" content="Browse professional services offered by talented students." />
      </Head>
      
      <WebHeader projectName={projectName} />
      
      <main className="flex-grow bg-gray-50 dark:bg-slate-900 min-h-screen">
        <section className="bg-indigo-600 py-16 text-white shadow-inner">
          <div className="container mx-auto px-6 text-center max-w-4xl">
            <h1 className="text-4xl md:text-5xl font-extrabold mb-6 tracking-tight uppercase">Student Service Directory</h1>
            <p className="text-xl opacity-90 leading-relaxed font-medium">Find talented student freelancers ready to help with your next tech project, marketing campaign, or business operations.</p>
          </div>
        </section>

        <SectionMain>
          <div className="mb-12 flex flex-col lg:flex-row gap-6 items-center justify-between bg-white dark:bg-slate-800 p-6 rounded-2xl border border-gray-100 dark:border-slate-700 shadow-sm">
            <div className="relative w-full lg:w-1/3">
              <span className="absolute inset-y-0 left-0 pl-4 flex items-center text-gray-400">
                <BaseIcon path={mdiMagnify} size={20} />
              </span>
              <input
                type="text"
                placeholder="Search by title, description, or skill..."
                className="block w-full pl-12 pr-4 py-3 border-2 border-gray-100 dark:border-slate-700 rounded-xl leading-5 bg-slate-50 dark:bg-slate-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all sm:text-sm font-medium"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            
            <div className="flex gap-3 overflow-x-auto pb-2 w-full lg:w-2/3 scroll-smooth no-scrollbar">
              <button 
                className={`px-6 py-2 rounded-full border-2 text-sm whitespace-nowrap font-bold transition-all ${!searchTerm ? 'bg-indigo-600 border-indigo-600 text-white shadow-md' : 'bg-white dark:bg-slate-800 border-gray-100 dark:border-slate-700 text-gray-600 dark:text-gray-400 hover:border-indigo-600 hover:text-indigo-600'}`}
                onClick={() => setSearchTerm('')}
              >
                All Services
              </button>
              {categories.map(cat => (
                <button 
                  key={cat.id}
                  className={`px-6 py-2 rounded-full border-2 text-sm whitespace-nowrap font-bold transition-all ${searchTerm === cat.name ? 'bg-indigo-600 border-indigo-600 text-white shadow-md' : 'bg-white dark:bg-slate-800 border-gray-100 dark:border-slate-700 text-gray-600 dark:text-gray-400 hover:border-indigo-600 hover:text-indigo-600'}`}
                  onClick={() => setSearchTerm(cat.name)}
                >
                  {cat.name}
                </button>
              ))}
            </div>
          </div>

          {loading ? (
            <div className="text-center py-32">
              <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-600 shadow-sm"></div>
              <p className="mt-6 text-gray-500 font-bold uppercase tracking-widest text-sm">Synchronizing Directory...</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
              {filteredServices.map((service) => (
                <CardBox key={service.id} className="hover:shadow-2xl transition-all duration-500 border-b-4 border-b-transparent hover:border-b-indigo-600">
                  <div className="flex flex-col h-full p-2">
                    <div className="flex justify-between items-start mb-6">
                      <h3 className="text-xl font-black text-gray-900 dark:text-white uppercase leading-tight tracking-tight">{service.title}</h3>
                      <div className="flex flex-col items-end">
                        <span className="text-2xl font-black text-indigo-600 dark:text-indigo-400 leading-none">${service.starting_price}</span>
                        <span className="text-[10px] uppercase font-bold text-gray-400 mt-1">Starting Price</span>
                      </div>
                    </div>
                    
                    <div 
                      className="text-gray-600 dark:text-gray-300 mb-8 line-clamp-4 text-sm font-medium leading-relaxed prose prose-sm dark:prose-invert"
                      dangerouslySetInnerHTML={{ __html: service.description }}
                    />

                    <div className="mt-auto pt-6 border-t-2 border-gray-50 dark:border-slate-800 flex items-center justify-between">
                      <div className="flex flex-col">
                        <span className="text-[10px] uppercase font-bold text-gray-400">Delivery</span>
                        <span className="text-sm font-black text-gray-900 dark:text-white uppercase">{service.delivery_days} Days</span>
                      </div>
                      <BaseButton
                        label="View Gig"
                        icon={mdiArrowRight}
                        color="indigo"
                        className="font-bold uppercase tracking-wider px-6"
                        href={`/web_pages/service-details?id=${service.id}`}
                      />
                    </div>
                  </div>
                </CardBox>
              ))}
            </div>
          )}

          {!loading && filteredServices.length === 0 && (
            <div className="text-center py-24 bg-white dark:bg-slate-800 rounded-3xl border-4 border-dashed border-gray-100 dark:border-slate-700">
              <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-slate-50 dark:bg-slate-900 text-gray-300 mb-6">
                <BaseIcon path={mdiMagnify} size={40} />
              </div>
              <h4 className="text-xl font-black text-gray-900 dark:text-white uppercase mb-2">No Matching Services</h4>
              <p className="text-gray-500 font-medium">Try broadening your search criteria or checking another category.</p>
              <BaseButton
                 className="mt-8"
                 label="Reset Filters"
                 onClick={() => setSearchTerm('')}
                 outline
                 color="indigo"
              />
            </div>
          )}
        </SectionMain>
      </main>

      <WebFooter projectName={projectName} />
    </>
  );
}

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