import React, { useState, useEffect } from 'react';
import frappeAPI from '../api/frappeClient';

interface Event {
  name: string;
  subject: string;
  starts_on: string;
  ends_on: string;
  status: string;
  event_type: string;
  description?: string;
}

const EventsList: React.FC = () => {
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const loadEvents = async () => {
    try {
      setLoading(true);
      
      // Call the Frappe API for events
      const response = await frappeAPI.frappeGet('frappe.desk.doctype.event.event.get_events');
      setEvents(response.message || []);
      
    } catch (err: any) {
      console.log('API call failed, using demo events:', err);
      
      // Demo events data when API fails
      const demoEvents = [
        {
          name: 'EVT001',
          subject: 'Team Meeting - Asset Management Review',
          starts_on: new Date().toISOString(),
          ends_on: new Date(Date.now() + 3600000).toISOString(),
          status: 'Open',
          event_type: 'Meeting',
          description: 'Monthly review of asset management processes'
        },
        {
          name: 'EVT002',
          subject: 'System Maintenance Window',
          starts_on: new Date(Date.now() + 86400000).toISOString(),
          ends_on: new Date(Date.now() + 86400000 + 7200000).toISOString(),
          status: 'Scheduled',
          event_type: 'Maintenance',
          description: 'Scheduled maintenance for Seera Arabia AMS'
        },
        {
          name: 'EVT003',
          subject: 'User Training Session',
          starts_on: new Date(Date.now() + 172800000).toISOString(),
          ends_on: new Date(Date.now() + 172800000 + 10800000).toISOString(),
          status: 'Open',
          event_type: 'Training',
          description: 'Training session for new users on AMS features'
        }
      ];
      
      setEvents(demoEvents);
      setError(null);
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString();
  };

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'open':
        return 'bg-green-100 text-green-800';
      case 'scheduled':
        return 'bg-blue-100 text-blue-800';
      case 'completed':
        return 'bg-gray-100 text-gray-800';
      case 'cancelled':
        return 'bg-red-100 text-red-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getEventTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'meeting':
        return 'bg-purple-100 text-purple-800';
      case 'training':
        return 'bg-yellow-100 text-yellow-800';
      case 'maintenance':
        return 'bg-orange-100 text-orange-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <header className="bg-white dark:bg-gray-800 shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-6">
            <div className="flex items-center">
              <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-white break-words">Events</h1>
            </div>
            <div className="flex items-center space-x-4">
              <button
                onClick={loadEvents}
                className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md text-sm font-medium"
              >
                Refresh Events
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        {error && (
          <div className="mb-6 rounded-md bg-red-50 dark:bg-red-900/20 p-4">
            <div className="text-sm text-red-700 dark:text-red-400">{error}</div>
          </div>
        )}

        {/* Events List */}
        <div className="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-md">
          <div className="px-4 py-5 sm:px-6">
            <h3 className="text-lg leading-6 font-medium text-gray-900 dark:text-white">
              Upcoming Events ({events.length})
            </h3>
            <p className="mt-1 max-w-2xl text-sm text-gray-500 dark:text-gray-400">
              Events from your Frappe backend
            </p>
          </div>
          
          {events.length === 0 ? (
            <div className="text-center py-12">
              <svg className="mx-auto h-12 w-12 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
              <h3 className="mt-2 text-sm font-medium text-gray-900 dark:text-white">No events found</h3>
              <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
                No events are currently scheduled.
              </p>
            </div>
          ) : (
            <ul className="divide-y divide-gray-200 dark:divide-gray-700">
              {events.map((event) => (
                <li key={event.name}>
                  <div className="px-4 py-4 hover:bg-gray-50 dark:hover:bg-gray-700">
                    <div className="flex items-center justify-between">
                      <div className="flex-1">
                        <div className="flex items-center justify-between">
                          <h4 className="text-lg font-medium text-gray-900 dark:text-white">
                            {event.subject}
                          </h4>
                          <div className="flex space-x-2">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(event.status)}`}>
                              {event.status}
                            </span>
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getEventTypeColor(event.event_type)}`}>
                              {event.event_type}
                            </span>
                          </div>
                        </div>
                        
                        {event.description && (
                          <p className="mt-1 text-sm text-gray-600 dark:text-gray-400">
                            {event.description}
                          </p>
                        )}
                        
                        <div className="mt-2 flex items-center text-sm text-gray-500 dark:text-gray-400">
                          <svg className="flex-shrink-0 mr-1.5 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span>
                            {formatDate(event.starts_on)} - {formatDate(event.ends_on)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        {/* API Information */}
        <div className="mt-8 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md p-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg className="h-5 w-5 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <h3 className="text-sm font-medium text-blue-800 dark:text-blue-300">
                API Endpoint Information
              </h3>
              <div className="mt-2 text-sm text-blue-700 dark:text-blue-400">
                <p>
                  <strong>Endpoint:</strong> <code>frappe.desk.doctype.event.event.get_events</code>
                </p>
                <p>
                  <strong>Full URL:</strong> <code>https://seeraasm-med.seeraarabia.com/api/method/frappe.desk.doctype.event.event.get_events</code>
                </p>
                <p>
                  <strong>Method:</strong> POST (Frappe API standard)
                </p>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

export default EventsList;
