import React, { useState } from 'react';
import { X, Truck, CheckCircle2, Loader2 } from 'lucide-react';

interface Props {
  open: boolean;
  close: () => void;
}

const DemoModal: React.FC<Props> = ({ open, close }) => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [company, setCompany] = useState('');
  const [smsOptIn, setSmsOptIn] = useState(true);
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState('');

  if (!open) return null;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email) {
      setError('Please enter your email.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      await fetch('https://famous.ai/api/crm/6a2ac9c527e83b3cec08fcb0/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email,
          name: name || undefined,
          phone: phone || undefined,
          sms_opt_in: smsOptIn === true,
          source: 'demo-request',
          tags: ['demo', 'fleet-lead', company || 'unknown-company'],
        }),
      });
      setDone(true);
    } catch {
      setError('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={close}>
      <div className="bg-white rounded-2xl w-full max-w-md overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-6 py-4 border-b border-slate-100">
          <div className="flex items-center gap-2">
            <div className="w-9 h-9 rounded-lg bg-[#0B3D91] flex items-center justify-center">
              <Truck className="w-5 h-5 text-white" />
            </div>
            <h2 className="font-semibold text-slate-900">Request a Demo</h2>
          </div>
          <button onClick={close} className="text-slate-400 hover:text-slate-600">
            <X className="w-5 h-5" />
          </button>
        </div>

        {done ? (
          <div className="p-8 text-center">
            <CheckCircle2 className="w-12 h-12 text-[#00C853] mx-auto mb-3" />
            <h3 className="font-semibold text-slate-900">You're on the list!</h3>
            <p className="text-sm text-slate-500 mt-1">Our team will reach out shortly to schedule your FleetFlow walkthrough.</p>
            <button onClick={close} className="mt-5 w-full py-2.5 rounded-lg bg-[#0B3D91] text-white text-sm font-semibold">
              Close
            </button>
          </div>
        ) : (
          <form onSubmit={submit} className="p-6 space-y-4">
            <p className="text-sm text-slate-500">See how FleetFlow cuts dispatcher workload by 50%. Enter your details and we'll be in touch.</p>
            <div>
              <label className="text-xs font-medium text-slate-600">Name</label>
              <input value={name} onChange={(e) => setName(e.target.value)} className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]" />
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600">Work Email *</label>
              <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]" />
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600">Phone number (optional)</label>
              <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]" />
            </div>
            <div>
              <label className="text-xs font-medium text-slate-600">Company / Fleet Size</label>
              <input value={company} onChange={(e) => setCompany(e.target.value)} placeholder="e.g. 12 trucks" className="w-full mt-1 text-sm rounded-lg border border-slate-200 px-3 py-2.5 outline-none focus:border-[#0B3D91]" />
            </div>
            <label className="flex items-start gap-2 text-xs text-slate-500">
              <input type="checkbox" checked={smsOptIn} onChange={(e) => setSmsOptIn(e.target.checked)} className="mt-0.5 accent-[#0B3D91]" />
              <span>Text me updates. Msg &amp; data rates may apply. Reply STOP to unsubscribe.</span>
            </label>
            {error && <p className="text-xs text-[#D32F2F]">{error}</p>}
            <button type="submit" disabled={loading} className="w-full flex items-center justify-center gap-2 py-2.5 rounded-lg bg-[#0B3D91] hover:bg-[#0a3580] disabled:opacity-60 text-white text-sm font-semibold">
              {loading && <Loader2 className="w-4 h-4 animate-spin" />}
              Request Demo
            </button>
          </form>
        )}
      </div>
    </div>
  );
};

export default DemoModal;
