'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import { MapPin, Phone, Mail, Clock, Send, CalendarDays, Building2, User, MessageSquare, Globe } from 'lucide-react';
import { toast } from 'sonner';

const serviceOptions = [
  'Tax Preparation',
  'Bookkeeping',
  'Payroll Services',
  'Sales Tax Submission',
  'General Inquiry',
];

const timeSlots = [
  '9:00 AM', '10:00 AM', '11:00 AM',
  '12:00 PM', '1:00 PM', '2:00 PM',
  '3:00 PM', '4:00 PM', '5:00 PM',
];

const inputClass = 'w-full pl-10 pr-4 py-3 rounded-xl border border-[var(--navy)]/[0.06] focus:border-[var(--gold)] focus:ring-2 focus:ring-[var(--gold)]/15 outline-none transition-all text-sm bg-white shadow-[var(--shadow-sm)]';
const selectClass = 'w-full px-4 py-3 rounded-xl border border-[var(--navy)]/[0.06] focus:border-[var(--gold)] focus:ring-2 focus:ring-[var(--gold)]/15 outline-none transition-all text-sm bg-white shadow-[var(--shadow-sm)]';

export function ContactContent() {
  const [activeTab, setActiveTab] = useState<'contact' | 'booking'>('contact');
  const [loading, setLoading] = useState(false);

  const [contactForm, setContactForm] = useState({
    name: '', email: '', phone: '', company: '', service: '', message: '',
  });

  const [bookingForm, setBookingForm] = useState({
    name: '', email: '', phone: '', company: '', service: 'Tax Preparation',
    preferredDate: '', preferredTime: '10:00 AM', notes: '',
  });

  const handleContact = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(contactForm),
      });
      if (res?.ok) {
        toast.success('Message sent successfully! We will get back to you shortly.');
        setContactForm({ name: '', email: '', phone: '', company: '', service: '', message: '' });
      } else {
        toast.error('Failed to send message. Please try again.');
      }
    } catch {
      toast.error('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleBooking = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      const res = await fetch('/api/booking', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(bookingForm),
      });
      if (res?.ok) {
        toast.success('Appointment request submitted! We will confirm your booking shortly.');
        setBookingForm({ name: '', email: '', phone: '', company: '', service: 'Tax Preparation', preferredDate: '', preferredTime: '10:00 AM', notes: '' });
      } else {
        toast.error('Failed to submit booking. Please try again.');
      }
    } catch {
      toast.error('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Hero */}
      <section className="relative py-20 sm:py-28 overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-[#081526] via-[#0d2137] to-[#1e4a6e]" />
        <div className="absolute inset-0 bg-mesh" />
        <div className="absolute inset-0 opacity-[0.03]" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, white 1px, transparent 0)', backgroundSize: '32px 32px' }} />
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 text-center relative">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6 }}>
            <span className="inline-block px-4 py-1.5 bg-white/[0.06] backdrop-blur-md border border-white/10 text-[var(--gold-light)] text-sm font-semibold rounded-full mb-4">Get In Touch</span>
            <h1 className="font-display text-4xl sm:text-5xl font-bold text-white tracking-tight mb-4">
              Contact <span className="text-gradient-gold">Us</span>
            </h1>
            <p className="text-white/60 text-lg max-w-2xl mx-auto">Ready to get started? Send us a message or schedule a free consultation today.</p>
          </motion.div>
        </div>
      </section>

      {/* Content */}
      <section className="py-16 sm:py-24">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 lg:grid-cols-5 gap-12">
            {/* Contact Info */}
            <div className="lg:col-span-2">
              <motion.div initial={{ opacity: 0, x: -20 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} transition={{ duration: 0.5 }}>
                <h2 className="font-display text-2xl font-bold text-[var(--navy)] mb-6">Let&apos;s Connect</h2>
                <div className="space-y-5">
                  {/* US Office */}
                  <div className="bg-[hsl(var(--muted))] rounded-2xl p-6">
                    <h3 className="font-semibold text-[var(--navy)] mb-3 flex items-center gap-2">
                      <Globe className="w-4 h-4 text-[var(--gold)]" /> US Office
                    </h3>
                    <div className="space-y-2.5 text-sm text-muted-foreground">
                      <div className="flex items-start gap-2.5">
                        <MapPin className="w-4 h-4 text-[var(--gold)] mt-0.5 shrink-0" />
                        502 West 7th Street, Suite 100, Erie, PA 16502, US
                      </div>
                      <a href="tel:+15707553434" className="flex items-center gap-2.5 hover:text-[var(--gold)] transition-colors">
                        <Phone className="w-4 h-4 text-[var(--gold)] shrink-0" />
                        +1 570-7553-434
                      </a>
                    </div>
                  </div>

                  {/* BD Office */}
                  <div className="bg-[hsl(var(--muted))] rounded-2xl p-6">
                    <h3 className="font-semibold text-[var(--navy)] mb-3 flex items-center gap-2">
                      <Globe className="w-4 h-4 text-[var(--gold)]" /> Bangladesh Office
                    </h3>
                    <div className="space-y-2.5 text-sm text-muted-foreground">
                      <div className="flex items-start gap-2.5">
                        <MapPin className="w-4 h-4 text-[var(--gold)] mt-0.5 shrink-0" />
                        Sayedpur West, Holding 56, Narayanganj Sadar-1400, BD
                      </div>
                      <a href="tel:+8801928802438" className="flex items-center gap-2.5 hover:text-[var(--gold)] transition-colors">
                        <Phone className="w-4 h-4 text-[var(--gold)] shrink-0" />
                        +88 01928802438
                      </a>
                    </div>
                  </div>

                  {/* Email & Hours */}
                  <div className="space-y-3">
                    <a href="mailto:Accounting@alphacpaconsulting.com" className="flex items-center gap-2.5 text-sm text-muted-foreground hover:text-[var(--gold)] transition-colors">
                      <Mail className="w-4 h-4 text-[var(--gold)] shrink-0" />
                      Accounting@alphacpaconsulting.com
                    </a>
                    <div className="flex items-center gap-2.5 text-sm text-muted-foreground">
                      <Clock className="w-4 h-4 text-[var(--gold)] shrink-0" />
                      Mon - Fri: 9:00 AM - 6:00 PM EST
                    </div>
                  </div>
                </div>

                <p className="text-xs text-muted-foreground mt-6">Your information is kept confidential and secure. We will never share your data with third parties.</p>
              </motion.div>
            </div>

            {/* Form */}
            <div className="lg:col-span-3">
              <motion.div initial={{ opacity: 0, x: 20 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} transition={{ duration: 0.5 }}>
                {/* Tabs */}
                <div className="flex bg-[hsl(var(--muted))] rounded-2xl p-1.5 mb-8">
                  <button
                    onClick={() => setActiveTab('contact')}
                    className={`flex-1 py-3 px-4 rounded-xl text-sm font-semibold transition-all flex items-center justify-center gap-2 ${
                      activeTab === 'contact' ? 'bg-gradient-to-r from-[var(--navy)] to-[var(--navy-light)] text-white shadow-lg shadow-[var(--navy)]/15' : 'text-muted-foreground hover:text-[var(--navy)]'
                    }`}
                  >
                    <MessageSquare className="w-4 h-4" /> Send Message
                  </button>
                  <button
                    onClick={() => setActiveTab('booking')}
                    className={`flex-1 py-3 px-4 rounded-xl text-sm font-semibold transition-all flex items-center justify-center gap-2 ${
                      activeTab === 'booking' ? 'bg-gradient-to-r from-[var(--navy)] to-[var(--navy-light)] text-white shadow-lg shadow-[var(--navy)]/15' : 'text-muted-foreground hover:text-[var(--navy)]'
                    }`}
                  >
                    <CalendarDays className="w-4 h-4" /> Book Appointment
                  </button>
                </div>

                {activeTab === 'contact' ? (
                  <form onSubmit={handleContact} className="space-y-5">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Full Name *</label>
                        <div className="relative">
                          <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input required value={contactForm?.name ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), name: e?.target?.value ?? '' }))} className={inputClass} placeholder="John Doe" />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Email *</label>
                        <div className="relative">
                          <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input required type="email" value={contactForm?.email ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), email: e?.target?.value ?? '' }))} className={inputClass} placeholder="john@example.com" />
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Phone</label>
                        <div className="relative">
                          <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input value={contactForm?.phone ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), phone: e?.target?.value ?? '' }))} className={inputClass} placeholder="(555) 123-4567" />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Company</label>
                        <div className="relative">
                          <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input value={contactForm?.company ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), company: e?.target?.value ?? '' }))} className={inputClass} placeholder="Your Company" />
                        </div>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Service Interested In</label>
                      <select value={contactForm?.service ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), service: e?.target?.value ?? '' }))} className={selectClass}>
                        <option value="">Select a service</option>
                        {serviceOptions?.map((s: string) => <option key={s} value={s}>{s}</option>)}
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Message *</label>
                      <textarea required rows={4} value={contactForm?.message ?? ''} onChange={(e: any) => setContactForm(prev => ({ ...(prev ?? {}), message: e?.target?.value ?? '' }))} className="w-full px-4 py-3 rounded-xl border border-[var(--navy)]/[0.06] focus:border-[var(--gold)] focus:ring-2 focus:ring-[var(--gold)]/15 outline-none transition-all text-sm bg-white shadow-[var(--shadow-sm)] resize-none" placeholder="How can we help you?" />
                    </div>
                    <button type="submit" disabled={loading} className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 bg-gradient-to-r from-[var(--navy)] to-[var(--navy-light)] text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-[var(--navy)]/20 transition-all duration-300 disabled:opacity-60">
                      {loading ? 'Sending...' : <><Send className="w-4 h-4" /> Send Message</>}
                    </button>
                  </form>
                ) : (
                  <form onSubmit={handleBooking} className="space-y-5">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Full Name *</label>
                        <div className="relative">
                          <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input required value={bookingForm?.name ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), name: e?.target?.value ?? '' }))} className={inputClass} placeholder="John Doe" />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Email *</label>
                        <div className="relative">
                          <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input required type="email" value={bookingForm?.email ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), email: e?.target?.value ?? '' }))} className={inputClass} placeholder="john@example.com" />
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Phone</label>
                        <div className="relative">
                          <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input value={bookingForm?.phone ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), phone: e?.target?.value ?? '' }))} className={inputClass} placeholder="(555) 123-4567" />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Company</label>
                        <div className="relative">
                          <Building2 className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input value={bookingForm?.company ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), company: e?.target?.value ?? '' }))} className={inputClass} placeholder="Your Company" />
                        </div>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Service *</label>
                      <select required value={bookingForm?.service ?? 'Tax Preparation'} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), service: e?.target?.value ?? '' }))} className={selectClass}>
                        {serviceOptions?.slice(0, 4)?.map((s: string) => <option key={s} value={s}>{s}</option>)}
                      </select>
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Preferred Date *</label>
                        <div className="relative">
                          <CalendarDays className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                          <input required type="date" value={bookingForm?.preferredDate ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), preferredDate: e?.target?.value ?? '' }))} className={inputClass} />
                        </div>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Preferred Time *</label>
                        <select required value={bookingForm?.preferredTime ?? '10:00 AM'} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), preferredTime: e?.target?.value ?? '' }))} className={selectClass}>
                          {timeSlots?.map((t: string) => <option key={t} value={t}>{t}</option>)}
                        </select>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-[var(--navy)] mb-1.5">Additional Notes</label>
                      <textarea rows={3} value={bookingForm?.notes ?? ''} onChange={(e: any) => setBookingForm(prev => ({ ...(prev ?? {}), notes: e?.target?.value ?? '' }))} className="w-full px-4 py-3 rounded-xl border border-[var(--navy)]/[0.06] focus:border-[var(--gold)] focus:ring-2 focus:ring-[var(--gold)]/15 outline-none transition-all text-sm bg-white shadow-[var(--shadow-sm)] resize-none" placeholder="Any specific topics you'd like to discuss?" />
                    </div>
                    <button type="submit" disabled={loading} className="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 bg-gradient-to-r from-[var(--gold)] to-[#d4b060] text-[var(--navy-dark)] font-semibold rounded-xl hover:shadow-lg hover:shadow-[var(--gold)]/20 transition-all duration-300 disabled:opacity-60">
                      {loading ? 'Submitting...' : <><CalendarDays className="w-4 h-4" /> Book Appointment</>}
                    </button>
                  </form>
                )}
              </motion.div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
