import React, { useEffect, useState } from 'react';
import type { ReactElement } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import axios from 'axios';
import LayoutGuest from '../../layouts/Guest';
import WebHeader from '../../components/WebHeader';
import WebFooter from '../../components/WebFooter';
import { useAppSelector } from '../../stores/hooks';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import { mdiCalendar, mdiCheckDecagram, mdiCurrencyUsd, mdiKeyboardReturn, mdiArrowLeft } from '@mdi/js';
import BaseIcon from '../../components/BaseIcon';

export default function ServiceDetailsPage() {
  const router = useRouter();
  const { id } = router.query;
  const projectName = useAppSelector((state) => state.style.projectName) || 'FreelanceFusion';
  const { currentUser } = useAppSelector((state) => state.auth);
  const [service, setService] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [purchasing, setPurchasing] = useState(false);

  useEffect(() => {
    if (id && typeof id === 'string') {
      const fetchService = async () => {
        try {
          const response = await axios.get(`/service_listings/${id}`);
          setService(response.data);
        } catch (err) {
          console.error('Failed to fetch service details:', err);
        } finally {
          setLoading(false);
        }
      };
      fetchService();
    }
  }, [id]);

  const handlePurchase = async () => {
    if (!currentUser) {
      router.push('/login');
      return;
    }
    
    setPurchasing(true);
    try {
      await axios.post(`/service_listings/${id}/purchase`);
      alert('Gig purchased successfully! Your funds are held safely in escrow.');
      router.push('/jobs/jobs-list');
    } catch (err: any) {
      console.error('Failed to purchase gig:', err);
      alert('Failed to purchase gig. Please try again.');
    } finally {
      setPurchasing(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col bg-gray-50 dark:bg-slate-900">
        <Head><title>Loading Gig Details...</title></Head>
        <WebHeader projectName={projectName} />
        <main className="flex-grow flex items-center justify-center py-32">
           <div className="flex flex-col items-center gap-6">
             <div className="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-indigo-600 shadow-xl"></div>
             <p className="font-black text-gray-500 uppercase tracking-widest text-sm">Gig Details Loading...</p>
           </div>
        </main>
        <WebFooter projectName={projectName} />
      </div>
    );
  }

  if (!service) {
    return (
      <div className="min-h-screen flex flex-col bg-gray-50 dark:bg-slate-900">
        <Head><title>Gig Not Found</title></Head>
        <WebHeader projectName={projectName} />
        <main className="flex-grow py-32 text-center container mx-auto px-6">
           <div className="bg-white dark:bg-slate-800 p-16 rounded-3xl border-4 border-dashed border-gray-100 dark:border-slate-700 max-w-2xl mx-auto shadow-2xl">
             <h2 className="text-3xl font-black text-gray-900 dark:text-white uppercase mb-4 tracking-tighter leading-tight">Gig Not Found</h2>
             <p className="text-lg text-gray-500 font-medium mb-8">The service listing you are looking for might have been removed or is no longer available.</p>
             <BaseButton 
                className="px-8 py-3 text-lg font-bold uppercase shadow-lg hover:shadow-indigo-200" 
                label="Back to Directory" 
                icon={mdiArrowLeft}
                onClick={() => router.push('/web_pages/services')} 
                color="indigo"
             />
           </div>
        </main>
        <WebFooter projectName={projectName} />
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col bg-gray-50 dark:bg-slate-900 font-sans">
      <Head>
        <title>{service.title} | {projectName}</title>
      </Head>
      
      <WebHeader projectName={projectName} />
      
      <main className="flex-grow">
        <section className="bg-white dark:bg-slate-800 border-b border-gray-100 dark:border-slate-800 py-20 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-96 h-96 bg-indigo-50 dark:bg-slate-900 rounded-full -mr-48 -mt-48 blur-3xl opacity-60"></div>
          <div className="absolute bottom-0 left-0 w-72 h-72 bg-pink-50 dark:bg-slate-900 rounded-full -ml-36 -mb-36 blur-3xl opacity-60"></div>
          
          <div className="container mx-auto px-6 max-w-6xl relative z-10">
            <div className="flex flex-col lg:flex-row gap-16">
              <div className="flex-grow lg:w-2/3">
                <nav className="text-xs text-gray-400 font-black uppercase tracking-widest mb-8 flex items-center gap-3">
                  <span className="hover:text-indigo-600 cursor-pointer transition-colors" onClick={() => router.push('/web_pages/services')}>Service Directory</span>
                  <span className="w-1 h-1 bg-gray-300 rounded-full"></span>
                  <span className="text-gray-900 dark:text-gray-200 tracking-normal normal-case">{service.title}</span>
                </nav>
                
                <h1 className="text-4xl md:text-5xl font-black text-gray-900 dark:text-white mb-8 leading-[1.1] tracking-tighter uppercase">
                  {service.title}
                </h1>
                
                <div className="flex items-center gap-6 mb-12 p-6 bg-slate-50 dark:bg-slate-900 rounded-2xl border border-gray-100 dark:border-slate-800 inline-flex max-w-md">
                   <div className="h-14 w-14 rounded-2xl bg-indigo-600 shadow-lg flex items-center justify-center text-white text-2xl font-black border-2 border-indigo-400">
                      {service.freelancer?.firstName?.[0] || 'S'}
                   </div>
                   <div>
                     <p className="font-black text-gray-900 dark:text-white uppercase tracking-tight text-lg">{service.freelancer?.firstName || 'Student Freelancer'}</p>
                     {service.freelancer?.is_verified_student ? (
                        <p className="text-sm text-green-600 dark:text-green-400 font-bold uppercase tracking-wider flex items-center gap-2">
                          <BaseIcon path={mdiCheckDecagram} className="text-green-500" size={16} />
                          Verified Student
                        </p>
                     ) : (
                        <p className="text-sm text-gray-500 font-bold uppercase tracking-wider flex items-center gap-2">
                           <BaseIcon path={mdiCheckDecagram} className="text-blue-500" size={16} />
                           Identity Verified
                        </p>
                     )}
                   </div>
                </div>

                <div className="prose prose-lg dark:prose-invert max-w-none text-gray-700 dark:text-gray-300 font-medium leading-relaxed prose-h3:uppercase prose-h3:font-black prose-h3:tracking-tighter prose-h3:text-2xl" 
                     dangerouslySetInnerHTML={{ __html: service.description }} />
              </div>

              <div className="w-full lg:w-1/3 flex-shrink-0">
                <div className="sticky top-24">
                  <CardBox className="border-4 border-indigo-600 shadow-2xl rounded-3xl overflow-hidden p-0 bg-white dark:bg-slate-800">
                    <div className="bg-indigo-600 p-8 text-white relative overflow-hidden">
                       <div className="absolute top-0 right-0 w-32 h-32 bg-white opacity-10 rounded-full -mr-16 -mt-16"></div>
                       <p className="text-5xl font-black mb-2 tracking-tighter leading-none">
                         ${service.starting_price}
                       </p>
                       <p className="text-xs font-black uppercase tracking-widest text-indigo-100">Starter Package Price</p>
                    </div>
                    
                    <div className="p-8 space-y-6">
                       <div className="flex items-center gap-4 text-gray-700 dark:text-gray-300 bg-slate-50 dark:bg-slate-900 p-4 rounded-xl border border-gray-100 dark:border-slate-700">
                         <BaseIcon path={mdiCalendar} className="text-indigo-600" size={24} />
                         <span className="text-base font-bold uppercase tracking-tight leading-none"><b>{service.delivery_days} Days</b> Delivery Time</span>
                       </div>
                       <div className="flex items-center gap-4 text-gray-700 dark:text-gray-300 bg-slate-50 dark:bg-slate-900 p-4 rounded-xl border border-gray-100 dark:border-slate-700">
                         <BaseIcon path={mdiKeyboardReturn} className="text-indigo-600" size={24} />
                         <span className="text-base font-bold uppercase tracking-tight leading-none"><b>Unlimited</b> Revisions</span>
                       </div>
                       
                       <BaseButton 
                         label={purchasing ? "Processing..." : (currentUser ? "Order Gig Instantly" : "Login to Order")} 
                         color="indigo" 
                         className="w-full mt-6 font-black py-5 text-xl uppercase tracking-widest shadow-xl hover:shadow-indigo-200 transition-all rounded-2xl"
                         onClick={handlePurchase}
                         disabled={purchasing}
                       />
                       
                       <div className="pt-6 border-t border-gray-50 dark:border-slate-700 text-center">
                          <p className="text-[10px] uppercase font-black text-gray-400 tracking-widest mb-2">Secure Gig Economy</p>
                          <div className="flex justify-center gap-4 opacity-30 grayscale hover:grayscale-0 transition-all">
                             <BaseIcon path={mdiCurrencyUsd} size={20} />
                          </div>
                       </div>
                    </div>
                  </CardBox>
                  
                  <div className="mt-8 p-6 bg-white dark:bg-slate-800 rounded-2xl border border-gray-100 dark:border-slate-800 shadow-sm flex items-center gap-4">
                     <div className="flex-shrink-0 w-10 h-10 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center text-green-600 dark:text-green-400">
                        <BaseIcon path={mdiCheckDecagram} size={20} />
                     </div>
                     <p className="text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-tight">Support local students and get high-quality work done at competitive rates.</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </main>

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

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