import React, { ReactElement, useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { 
  mdiShieldCheck, 
  mdiClockOutline, 
  mdiMapMarker, 
  mdiEmail,
  mdiAccount,
  mdiPhone,
  mdiAlertDecagram
} from '@mdi/js';
import { Formik, Form, Field } from 'formik';
import axios from 'axios';
import LayoutGuest from '../../layouts/Guest';
import BaseIcon from '../../components/BaseIcon';
import LoadingSpinner from '../../components/LoadingSpinner';
import FormField from '../../components/FormField';
import BaseButton from '../../components/BaseButton';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { create as createLead } from '../../stores/leads/leadsSlice';

const RequestServicePage = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { businessId } = router.query;
  const [business, setBusiness] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const { currentUser } = useAppSelector(state => state.auth);

  useEffect(() => {
    if (businessId) {
      fetchBusiness();
    }
  }, [businessId]);

  const fetchBusiness = async () => {
    try {
      const response = await axios.get(`/businesses/${businessId}`);
      setBusiness(response.data);
    } catch (error) {
      console.error('Error fetching business:', error);
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const payload = {
        ...values,
        businessId,
        user: currentUser?.id || null
      };
      await dispatch(createLead(payload)).unwrap();
      
      if (currentUser) {
        router.push('/leads/leads-list'); // Redirect to their leads tracker if logged in
      } else {
        alert('Your request has been sent! The professional will contact you soon.');
        router.push(`/public/businesses-details?id=${businessId}`);
      }
    } catch (error) {
      console.error('Lead creation error:', error);
      alert('There was an error sending your request. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  if (!business && businessId) return <div className="min-h-screen flex items-center justify-center bg-slate-50"><LoadingSpinner /></div>;

  return (
    <div className="min-h-screen bg-slate-50 pb-20 pt-28">
      <Head>
        <title>Request Service | Fix-It-Local™</title>
      </Head>

      <div className="container mx-auto px-6 max-w-4xl">
        <div className="bg-white rounded-[3rem] shadow-xl border border-slate-200 overflow-hidden">
          <div className="bg-slate-900 p-12 text-white relative">
            <div className="absolute top-0 right-0 p-12 opacity-10">
               <BaseIcon path={mdiShieldCheck} size={120} />
            </div>
            <h1 className="text-4xl font-bold mb-4">Request Service</h1>
            <p className="text-slate-400 text-lg max-w-xl">
              You are requesting a service from <span className="text-emerald-400 font-bold">{business?.name || 'a professional'}</span>. 
              Our smart matching system ensures your request is handled with priority.
            </p>
          </div>

          <div className="p-12">
            <Formik
              initialValues={{
                keyword: '',
                description: '',
                urgency: 'TODAY',
                contact_name: currentUser ? `${currentUser.firstName} ${currentUser.lastName}` : '',
                contact_email: currentUser?.email || '',
                contact_phone: currentUser?.phoneNumber || '',
                address: '',
                city: '',
                state: '',
                zip: ''
              }}
              onSubmit={handleSubmit}
            >
              {({ values }) => (
                <Form className="space-y-8">
                  <div className="grid md:grid-cols-2 gap-8">
                    <FormField label="What do you need help with?" labelFor="keyword">
                       <Field 
                        name="keyword" 
                        placeholder="e.g. Leaking faucet in kitchen" 
                        className="w-full bg-slate-50 border-slate-200 rounded-2xl py-4 px-6 focus:ring-emerald-500 focus:border-emerald-500"
                        required
                       />
                    </FormField>

                    <FormField label="Urgency" labelFor="urgency">
                       <Field 
                        name="urgency" 
                        as="select"
                        className="w-full bg-slate-50 border-slate-200 rounded-2xl py-4 px-6 focus:ring-emerald-500 focus:border-emerald-500"
                       >
                         <option value="EMERGENCY">🚨 Emergency (Immediate)</option>
                         <option value="TODAY">📅 Today</option>
                         <option value="THIS_WEEK">🗓️ This Week</option>
                         <option value="FLEXIBLE">🍃 Flexible</option>
                       </Field>
                    </FormField>
                  </div>

                  <FormField label="Details of the issue" labelFor="description">
                     <Field 
                      name="description" 
                      as="textarea"
                      rows={4}
                      placeholder="Please describe the problem in detail so the professional can give you an accurate estimate." 
                      className="w-full bg-slate-50 border-slate-200 rounded-2xl py-4 px-6 focus:ring-emerald-500 focus:border-emerald-500"
                      required
                     />
                  </FormField>

                  <div className="bg-slate-50 p-8 rounded-3xl space-y-8">
                    <h3 className="text-xl font-bold flex items-center">
                      <BaseIcon path={mdiAccount} size={24} className="mr-3 text-emerald-500" />
                      Contact Information
                    </h3>
                    
                    <div className="grid md:grid-cols-3 gap-6">
                      <FormField label="Your Name" labelFor="contact_name">
                        <Field name="contact_name" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                      </FormField>
                      <FormField label="Email" labelFor="contact_email">
                        <Field name="contact_email" type="email" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                      </FormField>
                      <FormField label="Phone" labelFor="contact_phone">
                        <Field name="contact_phone" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                      </FormField>
                    </div>

                    <div className="grid md:grid-cols-2 gap-6">
                      <FormField label="Service Address" labelFor="address">
                        <Field name="address" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                      </FormField>
                      <div className="grid grid-cols-3 gap-4">
                        <FormField label="City" labelFor="city">
                          <Field name="city" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                        </FormField>
                        <FormField label="State" labelFor="state">
                          <Field name="state" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                        </FormField>
                        <FormField label="ZIP" labelFor="zip">
                          <Field name="zip" className="w-full bg-white border-slate-200 rounded-xl py-3 px-4" required />
                        </FormField>
                      </div>
                    </div>
                  </div>

                  <div className="flex items-center justify-between pt-8 border-t border-slate-100">
                    <div className="text-slate-500 text-sm flex items-center max-w-sm">
                       <BaseIcon path={mdiShieldCheck} size={20} className="mr-2 text-emerald-500" />
                       Your data is protected and will only be shared with the professional you request.
                    </div>
                    <BaseButton 
                      type="submit" 
                      color="emerald" 
                      label={loading ? 'Submitting...' : 'Send Request'} 
                      className="py-5 px-12 rounded-2xl text-lg font-bold shadow-2xl shadow-emerald-500/30"
                      disabled={loading}
                    />
                  </div>
                </Form>
              )}
            </Formik>
          </div>
        </div>
      </div>
    </div>
  );
};

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

export default RequestServicePage;