import React, { useState, useEffect } from 'react';
import './styles.css';

interface AppointmentDetail {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  datetime: string;
  endTime: string;
  type: string;
  appointmentTypeID: number;
  calendarID: number;
  calendar: string;
  status: 'confirmed' | 'pending' | 'canceled';
  notes: string;
  price: string;
  paid: string;
  amountPaid: string;
  certificate: string;
  confirmationPage: string;
  formsText: string;
  labels: Array<{ id: number; name: string; color: string }>;
}

export default function AppointmentDetail() {
  const [appointment, setAppointment] = useState<AppointmentDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState(false);
  const [formData, setFormData] = useState({ firstName: '', lastName: '', email: '', phone: '', notes: '' });

  useEffect(() => {
    fetchAppointmentDetail();
  }, []);

  const fetchAppointmentDetail = async () => {
    setLoading(true);
    try {
      // In production: const appointment = await window.mcp.call('acuity_get_appointment', { id: appointmentId });
      
      // Mock data
      const mockAppointment: AppointmentDetail = {
        id: 12345,
        firstName: 'John',
        lastName: 'Doe',
        email: 'john.doe@example.com',
        phone: '(555) 123-4567',
        datetime: '2024-02-15T10:00:00',
        endTime: '2024-02-15T11:00:00',
        type: 'Initial Consultation',
        appointmentTypeID: 1,
        calendarID: 1,
        calendar: 'Main Calendar',
        status: 'confirmed',
        notes: 'Client prefers morning appointments. First-time visitor.',
        price: '$150.00',
        paid: 'yes',
        amountPaid: '$150.00',
        certificate: '',
        confirmationPage: 'https://acuityscheduling.com/confirmation',
        formsText: 'Intake form completed',
        labels: [
          { id: 1, name: 'VIP', color: '#fbbf24' },
          { id: 2, name: 'New Client', color: '#3b82f6' }
        ]
      };
      
      setAppointment(mockAppointment);
      setFormData({
        firstName: mockAppointment.firstName,
        lastName: mockAppointment.lastName,
        email: mockAppointment.email,
        phone: mockAppointment.phone,
        notes: mockAppointment.notes
      });
    } catch (error) {
      console.error('Error fetching appointment:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdate = async () => {
    if (!appointment) return;
    
    try {
      // In production: await window.mcp.call('acuity_update_appointment', { id: appointment.id, ...formData });
      console.log('Updating appointment:', formData);
      setEditing(false);
      await fetchAppointmentDetail();
    } catch (error) {
      console.error('Error updating appointment:', error);
    }
  };

  const handleCancel = async () => {
    if (!appointment || !confirm('Are you sure you want to cancel this appointment?')) return;
    
    try {
      // In production: await window.mcp.call('acuity_cancel_appointment', { id: appointment.id });
      console.log('Canceling appointment:', appointment.id);
      await fetchAppointmentDetail();
    } catch (error) {
      console.error('Error canceling appointment:', error);
    }
  };

  const handleReschedule = async () => {
    if (!appointment) return;
    const newDatetime = prompt('Enter new datetime (ISO 8601 format):');
    if (!newDatetime) return;
    
    try {
      // In production: await window.mcp.call('acuity_reschedule_appointment', { id: appointment.id, datetime: newDatetime });
      console.log('Rescheduling to:', newDatetime);
      await fetchAppointmentDetail();
    } catch (error) {
      console.error('Error rescheduling appointment:', error);
    }
  };

  if (loading) {
    return (
      <div className="loading">
        <div className="spinner"></div>
        <p>Loading appointment details...</p>
      </div>
    );
  }

  if (!appointment) {
    return (
      <div className="error-state">
        <h2>Appointment not found</h2>
      </div>
    );
  }

  return (
    <div className="appointment-detail">
      <header className="detail-header">
        <div>
          <h1>Appointment #{appointment.id}</h1>
          <span className={`status-badge status-${appointment.status}`}>
            {appointment.status.charAt(0).toUpperCase() + appointment.status.slice(1)}
          </span>
        </div>
        <div className="header-actions">
          {!editing && <button onClick={() => setEditing(true)}>✏️ Edit</button>}
          <button onClick={handleReschedule}>🔄 Reschedule</button>
          <button className="danger" onClick={handleCancel}>❌ Cancel</button>
        </div>
      </header>

      <div className="detail-grid">
        <section className="detail-card">
          <h2>Client Information</h2>
          {editing ? (
            <div className="edit-form">
              <div className="form-group">
                <label>First Name</label>
                <input 
                  type="text" 
                  value={formData.firstName}
                  onChange={(e) => setFormData({...formData, firstName: e.target.value})}
                />
              </div>
              <div className="form-group">
                <label>Last Name</label>
                <input 
                  type="text" 
                  value={formData.lastName}
                  onChange={(e) => setFormData({...formData, lastName: e.target.value})}
                />
              </div>
              <div className="form-group">
                <label>Email</label>
                <input 
                  type="email" 
                  value={formData.email}
                  onChange={(e) => setFormData({...formData, email: e.target.value})}
                />
              </div>
              <div className="form-group">
                <label>Phone</label>
                <input 
                  type="tel" 
                  value={formData.phone}
                  onChange={(e) => setFormData({...formData, phone: e.target.value})}
                />
              </div>
              <div className="edit-actions">
                <button onClick={handleUpdate}>💾 Save</button>
                <button onClick={() => setEditing(false)}>Cancel</button>
              </div>
            </div>
          ) : (
            <div className="info-list">
              <div className="info-item">
                <span className="label">Name:</span>
                <span className="value">{appointment.firstName} {appointment.lastName}</span>
              </div>
              <div className="info-item">
                <span className="label">Email:</span>
                <span className="value">{appointment.email}</span>
              </div>
              <div className="info-item">
                <span className="label">Phone:</span>
                <span className="value">{appointment.phone}</span>
              </div>
            </div>
          )}
        </section>

        <section className="detail-card">
          <h2>Appointment Details</h2>
          <div className="info-list">
            <div className="info-item">
              <span className="label">Type:</span>
              <span className="value">{appointment.type}</span>
            </div>
            <div className="info-item">
              <span className="label">Calendar:</span>
              <span className="value">{appointment.calendar}</span>
            </div>
            <div className="info-item">
              <span className="label">Date & Time:</span>
              <span className="value">{new Date(appointment.datetime).toLocaleString()}</span>
            </div>
            <div className="info-item">
              <span className="label">Duration:</span>
              <span className="value">60 minutes</span>
            </div>
          </div>
        </section>

        <section className="detail-card">
          <h2>Payment</h2>
          <div className="info-list">
            <div className="info-item">
              <span className="label">Price:</span>
              <span className="value">{appointment.price}</span>
            </div>
            <div className="info-item">
              <span className="label">Paid:</span>
              <span className="value">{appointment.paid === 'yes' ? '✅ Yes' : '❌ No'}</span>
            </div>
            <div className="info-item">
              <span className="label">Amount Paid:</span>
              <span className="value">{appointment.amountPaid}</span>
            </div>
          </div>
        </section>

        <section className="detail-card full-width">
          <h2>Labels</h2>
          <div className="labels-list">
            {appointment.labels.map(label => (
              <span key={label.id} className="label-badge" style={{ backgroundColor: label.color + '20', color: label.color }}>
                {label.name}
              </span>
            ))}
          </div>
        </section>

        <section className="detail-card full-width">
          <h2>Notes</h2>
          {editing ? (
            <textarea 
              value={formData.notes}
              onChange={(e) => setFormData({...formData, notes: e.target.value})}
              rows={4}
            />
          ) : (
            <p className="notes-text">{appointment.notes || 'No notes'}</p>
          )}
        </section>
      </div>
    </div>
  );
}
