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

interface Appointment {
  id: number;
  firstName: string;
  lastName: string;
  datetime: string;
  type: string;
  calendar: string;
  status: 'confirmed' | 'pending' | 'canceled';
  email: string;
  phone: string;
}

export default function AppointmentGrid() {
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState({ status: 'all', calendar: 'all', search: '' });
  const [sortBy, setSortBy] = useState<'datetime' | 'name' | 'status'>('datetime');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

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

  const fetchAppointments = async () => {
    setLoading(true);
    try {
      // Mock data
      const mockAppointments: Appointment[] = Array.from({ length: 25 }, (_, i) => ({
        id: i + 1,
        firstName: ['John', 'Jane', 'Bob', 'Alice', 'Charlie'][i % 5],
        lastName: ['Doe', 'Smith', 'Johnson', 'Williams', 'Brown'][i % 5],
        datetime: new Date(Date.now() + i * 3600000 * 24).toISOString(),
        type: ['Consultation', 'Follow-up', 'Assessment', 'Check-in'][i % 4],
        calendar: ['Main Calendar', 'Secondary Calendar'][i % 2],
        status: (['confirmed', 'pending', 'canceled'] as const)[i % 3],
        email: `client${i}@example.com`,
        phone: `(555) ${String(i).padStart(3, '0')}-4567`
      }));
      setAppointments(mockAppointments);
    } catch (error) {
      console.error('Error fetching appointments:', error);
    } finally {
      setLoading(false);
    }
  };

  const filteredAppointments = appointments
    .filter(apt => {
      if (filter.status !== 'all' && apt.status !== filter.status) return false;
      if (filter.calendar !== 'all' && apt.calendar !== filter.calendar) return false;
      if (filter.search) {
        const search = filter.search.toLowerCase();
        return (
          apt.firstName.toLowerCase().includes(search) ||
          apt.lastName.toLowerCase().includes(search) ||
          apt.email.toLowerCase().includes(search)
        );
      }
      return true;
    })
    .sort((a, b) => {
      let aVal, bVal;
      switch (sortBy) {
        case 'name':
          aVal = `${a.firstName} ${a.lastName}`;
          bVal = `${b.firstName} ${b.lastName}`;
          break;
        case 'status':
          aVal = a.status;
          bVal = b.status;
          break;
        default:
          aVal = new Date(a.datetime).getTime();
          bVal = new Date(b.datetime).getTime();
      }
      const result = aVal > bVal ? 1 : -1;
      return sortOrder === 'asc' ? result : -result;
    });

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

  return (
    <div className="appointment-grid-container">
      <header>
        <h1>Appointment Grid</h1>
        <button className="refresh-btn" onClick={fetchAppointments}>🔄 Refresh</button>
      </header>

      <div className="filters">
        <input
          type="text"
          placeholder="Search by name or email..."
          value={filter.search}
          onChange={(e) => setFilter({...filter, search: e.target.value})}
          className="search-input"
        />
        <select value={filter.status} onChange={(e) => setFilter({...filter, status: e.target.value})}>
          <option value="all">All Statuses</option>
          <option value="confirmed">Confirmed</option>
          <option value="pending">Pending</option>
          <option value="canceled">Canceled</option>
        </select>
        <select value={filter.calendar} onChange={(e) => setFilter({...filter, calendar: e.target.value})}>
          <option value="all">All Calendars</option>
          <option value="Main Calendar">Main Calendar</option>
          <option value="Secondary Calendar">Secondary Calendar</option>
        </select>
        <select value={sortBy} onChange={(e) => setSortBy(e.target.value as any)}>
          <option value="datetime">Sort by Date</option>
          <option value="name">Sort by Name</option>
          <option value="status">Sort by Status</option>
        </select>
        <button onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}>
          {sortOrder === 'asc' ? '↑' : '↓'}
        </button>
      </div>

      <div className="grid-stats">
        <span>Total: {filteredAppointments.length}</span>
        <span>Confirmed: {filteredAppointments.filter(a => a.status === 'confirmed').length}</span>
        <span>Pending: {filteredAppointments.filter(a => a.status === 'pending').length}</span>
      </div>

      <div className="grid-table">
        <table>
          <thead>
            <tr>
              <th>ID</th>
              <th>Client</th>
              <th>Email</th>
              <th>Phone</th>
              <th>Date & Time</th>
              <th>Type</th>
              <th>Calendar</th>
              <th>Status</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {filteredAppointments.map(apt => (
              <tr key={apt.id}>
                <td>#{apt.id}</td>
                <td className="client-cell">{apt.firstName} {apt.lastName}</td>
                <td>{apt.email}</td>
                <td>{apt.phone}</td>
                <td>{new Date(apt.datetime).toLocaleString()}</td>
                <td>{apt.type}</td>
                <td>{apt.calendar}</td>
                <td>
                  <span className={`status-badge status-${apt.status}`}>
                    {apt.status}
                  </span>
                </td>
                <td>
                  <button className="action-btn">View</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
