import { useState, useEffect } from 'react';

export default function BookingFlow() {
  const [step, setStep] = useState(1);
  const [types, setTypes] = useState<any[]>([]);
  const [selectedType, setSelectedType] = useState<any>(null);
  const [availableTimes, setAvailableTimes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_list_appointment_types', params: {} }, '*');
  }, []);

  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data.type === 'mcp-result') {
        const result = JSON.parse(e.data.result);
        if (Array.isArray(result)) {
          setTypes(result);
          setLoading(false);
        } else if (result.time) {
          setAvailableTimes(prev => [...prev, result]);
        }
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);

  const selectType = (type: any) => {
    setSelectedType(type);
    setStep(2);
    window.parent.postMessage({ type: 'mcp-call', method: 'acuity_get_availability_times', params: { appointmentTypeID: type.id, date: new Date().toISOString().split('T')[0] } }, '*');
  };

  if (loading) return <div style={{ padding: '20px' }}>Loading...</div>;

  return (
    <div style={{ padding: '20px', fontFamily: 'system-ui, sans-serif' }}>
      <header style={{ marginBottom: '20px' }}>
        <h1 style={{ margin: 0, fontSize: '24px' }}>Book an Appointment</h1>
        <div style={{ marginTop: '10px', fontSize: '14px', color: '#666' }}>Step {step} of 3</div>
      </header>

      {step === 1 && (
        <section>
          <h2 style={{ fontSize: '18px', marginBottom: '15px' }}>Select Service</h2>
          <div style={{ display: 'grid', gap: '10px' }}>
            {types.map((type: any) => (
              <div key={type.id} onClick={() => selectType(type)} style={{ border: '1px solid #ddd', padding: '15px', borderRadius: '8px', cursor: 'pointer', transition: 'all 0.2s' }}>
                <div style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '5px' }}>{type.name}</div>
                <div style={{ fontSize: '14px', color: '#666' }}>{type.duration} minutes - ${type.price}</div>
              </div>
            ))}
          </div>
        </section>
      )}

      {step === 2 && selectedType && (
        <section>
          <h2 style={{ fontSize: '18px', marginBottom: '15px' }}>Select Time for {selectedType.name}</h2>
          <div style={{ display: 'grid', gap: '10px' }}>
            {availableTimes.map((slot: any, i: number) => (
              <div key={i} onClick={() => setStep(3)} style={{ border: '1px solid #ddd', padding: '12px', borderRadius: '8px', cursor: 'pointer', textAlign: 'center' }}>
                {slot.time}
              </div>
            ))}
          </div>
          <button onClick={() => setStep(1)} style={{ marginTop: '20px', padding: '10px 20px', background: '#6c757d', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>Back</button>
        </section>
      )}

      {step === 3 && (
        <section>
          <h2 style={{ fontSize: '18px', marginBottom: '15px' }}>Enter Your Information</h2>
          <form style={{ display: 'grid', gap: '15px' }}>
            <input type="text" placeholder="First Name" required style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '4px' }} />
            <input type="text" placeholder="Last Name" required style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '4px' }} />
            <input type="email" placeholder="Email" required style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '4px' }} />
            <input type="tel" placeholder="Phone" style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '4px' }} />
            <button type="submit" style={{ padding: '12px', background: '#28a745', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer', fontSize: '16px' }}>Confirm Booking</button>
          </form>
          <button onClick={() => setStep(2)} style={{ marginTop: '15px', padding: '10px 20px', background: '#6c757d', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>Back</button>
        </section>
      )}
    </div>
  );
}
