'use client';
import { useState } from 'react';
import { motion } from 'framer-motion';
import { MapPin, Phone, Mail, Send, CheckCircle2, AlertCircle } from 'lucide-react';
import { toast } from 'sonner';
import { useLanguage } from '@/lib/i18n/language-context';

export function ContactClient({ vehicle }: { vehicle: any }) {
  const { t } = useLanguage();
  const [form, setForm] = useState({
    name: '',
    email: '',
    phone: '',
    message: vehicle ? `${t.contact.interestedIn} ${vehicle?.title ?? ''}` : '',
  });
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const handleSubmit = async (e: any) => {
    e?.preventDefault?.();
    if (!form?.name || !form?.email || !form?.message) {
      toast?.error?.(t.contact.errorRequired);
      return;
    }
    setLoading(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...(form ?? {}), vehicleId: vehicle?.id ?? null, source: 'CONTACT_FORM' }),
      });
      if (res?.ok) {
        setSent(true);
        toast?.success?.(t.contact.successToast);
        // Track lead conversion in GA
        if (typeof window !== 'undefined' && typeof (window as any).gtag === 'function') {
          (window as any).gtag('event', 'generate_lead', {
            event_category: 'Contact',
            event_label: vehicle?.title || 'General Inquiry',
            value: 1,
          });
        }
      } else {
        toast?.error?.(t.contact.errorSend);
      }
    } catch {
      toast?.error?.(t.contact.errorConnection);
    }
    setLoading(false);
  };

  if (sent) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <motion.div initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="text-center">
          <CheckCircle2 className="w-16 h-16 text-green-500 mx-auto mb-4" />
          <h2 className="font-display text-2xl font-bold">{t.contact.successTitle}</h2>
          <p className="text-gray-500 mt-2">{t.contact.successDesc}</p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="bg-[#faf5ef] min-h-screen">
      {/* Header */}
      <div className="bg-[#1a1a1a] py-12">
        <div className="max-w-[1200px] mx-auto px-4">
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}>
            <h1 className="font-display text-3xl md:text-4xl font-bold text-white tracking-tight">{t.contact.title}</h1>
            <p className="text-gray-400 mt-2">{t.contact.subtitle}</p>
          </motion.div>
        </div>
      </div>

      <div className="max-w-[1200px] mx-auto px-4 py-12">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Contact info */}
          <div className="space-y-6">
            {[
              { icon: MapPin, title: t.contact.address, info: '1444 North Broad St, Hillside NJ 07205' },
              { icon: Phone, title: t.contact.phones, info: '(908) 590-9802 / (908) 343-6096' },
              { icon: Mail, title: t.contact.email, info: 'junior@evotrucksales.com / kein@evotrucksales.com' },
            ]?.map((c: any, i: number) => (
              <motion.div key={i} initial={{ opacity: 0, x: -20 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} transition={{ delay: i * 0.1 }} className="bg-white rounded-xl p-6 shadow-md flex items-start gap-4">
                <div className="w-10 h-10 rounded-lg bg-red-50 flex items-center justify-center shrink-0">
                  <c.icon className="w-5 h-5 text-red-600" />
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">{c?.title ?? ''}</h3>
                  <p className="text-gray-700 text-sm mt-1">{c?.info ?? ''}</p>
                </div>
              </motion.div>
            ))}
          </div>

          {/* Form */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="lg:col-span-2">
            <form onSubmit={handleSubmit} className="bg-white rounded-xl shadow-md p-8">
              <h2 className="font-display text-xl font-bold mb-6">{t.contact.formTitle}</h2>
              {vehicle && (
                <div className="bg-red-50 text-red-700 text-sm rounded-lg p-3 mb-4 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4 shrink-0" />
                  {t.contact.inquiryAbout} <strong>{vehicle?.title ?? ''}</strong>
                </div>
              )}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">{t.contact.name}</label>
                  <input type="text" required value={form?.name ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), name: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none" placeholder={t.contact.namePlaceholder} />
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">{t.contact.emailLabel}</label>
                  <input type="email" required value={form?.email ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), email: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none" placeholder={t.contact.emailPlaceholder} />
                </div>
              </div>
              <div className="mt-4">
                <label className="text-sm font-medium text-gray-700 mb-1 block">{t.contact.phone}</label>
                <input type="tel" value={form?.phone ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), phone: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none" placeholder={t.contact.phonePlaceholder} />
              </div>
              <div className="mt-4">
                <label className="text-sm font-medium text-gray-700 mb-1 block">{t.contact.message}</label>
                <textarea required rows={5} value={form?.message ?? ''} onChange={(e: any) => setForm({ ...(form ?? {}), message: e?.target?.value ?? '' })} className="w-full border border-gray-200 rounded-lg px-4 py-3 text-sm focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none resize-none" placeholder={t.contact.messagePlaceholder} />
              </div>
              <p className="text-xs text-gray-400 mt-2">{t.contact.privacy}</p>
              <button type="submit" disabled={loading} className="mt-6 w-full bg-red-600 hover:bg-red-700 disabled:bg-gray-400 text-white px-6 py-3.5 rounded-lg font-semibold text-sm transition flex items-center justify-center gap-2">
                {loading ? t.contact.sending : <><Send className="w-4 h-4" /> {t.contact.send}</>}
              </button>
            </form>
          </motion.div>
        </div>
      </div>
    </div>
  );
}
