import { useState } from 'react';
import { supabase } from '../lib/supabase';
import { ArrowRight, CheckCircle, Loader2 } from 'lucide-react';
import Reveal from '../components/ui/Reveal';

const projectTypes = [
  'General Contracting', 'Renovation', 'Interior Finishing',
  'Painting', 'Other',
];

const budgetRanges = [
  'Under $10,000', '$10,000 – $50,000', '$50,000 – $150,000',
  '$150,000 – $500,000', '$500,000 – $1M', 'Over $1M', 'Not sure yet',
];

type Form = { name: string; phone: string; email: string; project_type: string; budget: string; location: string; message: string };
const init: Form = { name: '', phone: '', email: '', project_type: '', budget: '', location: '', message: '' };

export default function Inquiries() {
  const [form, setForm] = useState<Form>(init);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState('');

  const change = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) =>
    setForm((p) => ({ ...p, [e.target.name]: e.target.value }));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const { error: err } = await supabase.from('inquiries').insert({ ...form, budget: form.budget || null });
      if (err) throw err;
      setSuccess(true);
      setForm(init);
    } catch {
      setError('Something went wrong. Please try again or call us directly.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="pt-24">
      {/* Header */}
      <section
        className="relative py-28 bg-cover bg-center"
        style={{ backgroundImage: 'url(https://images.pexels.com/photos/834892/pexels-photo-834892.jpeg?auto=compress&cs=tinysrgb&w=1920)' }}
      >
        <div className="absolute inset-0 bg-navy/84" />
        <div className="relative z-10 max-w-7xl mx-auto px-6 lg:px-12">
          <span className="section-label">Get Started</span>
          <h1 className="section-title-light max-w-xl">
            Request a<br /><span className="text-gold italic">Free Quote</span>
          </h1>
          <p className="font-sans text-white/55 text-sm max-w-lg mt-5 leading-relaxed">
            Fill out the form below and we'll get back to you within 24 hours to arrange a free site consultation.
          </p>
        </div>
      </section>

      {/* Form */}
      <section className="py-24 bg-cream-200">
        <div className="max-w-6xl mx-auto px-6 lg:px-12">
          <div className="grid lg:grid-cols-3 gap-16">
            {/* Side Info */}
            <Reveal direction="left" className="lg:col-span-1">
              <h2 className="font-serif text-2xl text-navy mb-8">How It Works</h2>
              <div className="space-y-8">
                {[
                  { n: '01', t: 'Submit Your Inquiry', d: 'Complete the form with your project details.' },
                  { n: '02', t: 'We Review & Call', d: 'Our team reviews your request and calls within 24 hours.' },
                  { n: '03', t: 'Free Site Visit', d: 'We visit your site for a full assessment at no charge.' },
                  { n: '04', t: 'Written Quotation', d: 'Receive a detailed, transparent quote within 48 hours.' },
                ].map((s) => (
                  <div key={s.n} className="flex gap-4">
                    <span className="font-serif text-2xl text-gold/35 leading-none flex-shrink-0 w-8">{s.n}</span>
                    <div>
                      <h4 className="font-sans text-sm font-medium text-navy mb-1">{s.t}</h4>
                      <p className="font-sans text-xs text-navy/50 leading-relaxed">{s.d}</p>
                    </div>
                  </div>
                ))}
              </div>

              <div className="mt-12 bg-navy p-6">
                <p className="font-sans text-[10px] tracking-[0.18em] uppercase text-gold mb-3">Prefer to call?</p>
                <a href="tel:+97444412853" className="font-sans text-white text-sm block mb-0.5">+974 4441 2853</a>
                <p className="font-sans text-white/50 text-xs">Mon–Sat, 7am – 6pm</p>
              </div>
            </Reveal>

            {/* Form */}
            <Reveal direction="right" className="lg:col-span-2">
              {success ? (
                <div className="bg-white border border-sand-200 p-12 text-center">
                  <div className="w-14 h-14 bg-gold/10 border border-gold/30 flex items-center justify-center mx-auto mb-6">
                    <CheckCircle size={28} className="text-gold" />
                  </div>
                  <h3 className="font-serif text-2xl text-navy mb-4">Inquiry Submitted</h3>
                  <p className="font-sans text-navy/55 text-sm leading-relaxed max-w-sm mx-auto mb-8">
                    Thank you! We'll review your inquiry and call you within 24 hours to arrange a site visit.
                  </p>
                  <button onClick={() => setSuccess(false)} className="btn-outline-dark">Submit Another</button>
                </div>
              ) : (
                <form onSubmit={submit} className="bg-white border border-sand-200 p-8 md:p-12">
                  <h3 className="font-serif text-2xl text-navy mb-8">Project Details</h3>

                  <div className="grid md:grid-cols-2 gap-5 mb-5">
                    <div>
                      <label className="input-label">Full Name *</label>
                      <input name="name" value={form.name} onChange={change} required placeholder="Your name" className="input-field" />
                    </div>
                    <div>
                      <label className="input-label">Phone Number *</label>
                      <input name="phone" value={form.phone} onChange={change} required placeholder="+974 xxxx xxxx" className="input-field" />
                    </div>
                  </div>

                  <div className="grid md:grid-cols-2 gap-5 mb-5">
                    <div>
                      <label className="input-label">Email Address *</label>
                      <input name="email" type="email" value={form.email} onChange={change} required placeholder="you@example.com" className="input-field" />
                    </div>
                    <div>
                      <label className="input-label">Project Type *</label>
                      <select name="project_type" value={form.project_type} onChange={change} required className="input-field">
                        <option value="">Select...</option>
                        {projectTypes.map((t) => <option key={t} value={t}>{t}</option>)}
                      </select>
                    </div>
                  </div>

                  <div className="grid md:grid-cols-2 gap-5 mb-5">
                    <div>
                      <label className="input-label">Approximate Budget</label>
                      <select name="budget" value={form.budget} onChange={change} className="input-field">
                        <option value="">Not specified</option>
                        {budgetRanges.map((b) => <option key={b} value={b}>{b}</option>)}
                      </select>
                    </div>
                    <div>
                      <label className="input-label">Project Location *</label>
                      <input name="location" value={form.location} onChange={change} required placeholder="City, State" className="input-field" />
                    </div>
                  </div>

                  <div className="mb-8">
                    <label className="input-label">Project Description *</label>
                    <textarea
                      name="message"
                      value={form.message}
                      onChange={change}
                      required
                      rows={5}
                      placeholder="Describe your project — scope, timeline, any specific requirements..."
                      className="input-field resize-none"
                    />
                  </div>

                  {error && <div className="mb-5 p-4 bg-red-50 border border-red-200"><p className="font-sans text-sm text-red-600">{error}</p></div>}

                  <button type="submit" disabled={loading} className="btn-primary w-full justify-center disabled:opacity-70">
                    {loading
                      ? <><Loader2 size={14} className="animate-spin" /> Submitting...</>
                      : <>Submit Inquiry <ArrowRight size={13} /></>}
                  </button>
                </form>
              )}
            </Reveal>
          </div>
        </div>
      </section>
    </div>
  );
}
