import React, { useState, useEffect } from 'react';

interface CustomPricingProfile {
  id: string;
  user_id: string;
  stripe_account_id?: string;
  use_personal_stripe: boolean;
  can_override_pricing: boolean;
  can_set_custom_fees: boolean;
  custom_platform_fee_type?: 'percentage' | 'fixed' | 'none';
  custom_platform_fee_percentage?: number;
  custom_platform_fee_fixed?: number;
}

interface Event {
  id: string;
  title: string;
  start_time: string;
  organizations: {
    name: string;
  };
}

interface EventPricingOverride {
  id: string;
  event_id: string;
  use_custom_stripe_account: boolean;
  override_platform_fees: boolean;
  platform_fee_type?: 'percentage' | 'fixed' | 'none';
  platform_fee_percentage?: number;
  platform_fee_fixed?: number;
}

interface CustomPricingManagerProps {
  userId: string;
  isAdmin: boolean;
}

const CustomPricingManager: React.FC<CustomPricingManagerProps> = ({
  userId,
  isAdmin
}) => {
  const [profile, setProfile] = useState<CustomPricingProfile | null>(null);
  const [events, setEvents] = useState<Event[]>([]);
  const [eventOverrides, setEventOverrides] = useState<EventPricingOverride[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'profile' | 'events'>('profile');
  const [showEventModal, setShowEventModal] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<Event | null>(null);

  useEffect(() => {
    if (isAdmin) {
      loadData();
    }
  }, [userId, isAdmin]);

  const loadData = async () => {
    try {
      const [profileRes, eventsRes, overridesRes] = await Promise.all([
        fetch(`/api/custom-pricing/profile/${userId}`),
        fetch(`/api/events?user_id=${userId}`),
        fetch(`/api/custom-pricing/overrides?user_id=${userId}`)
      ]);

      const profileData = await profileRes.json();
      const eventsData = await eventsRes.json();
      const overridesData = await overridesRes.json();

      if (profileData.success) setProfile(profileData.profile);
      if (eventsData.success) setEvents(eventsData.events);
      if (overridesData.success) setEventOverrides(overridesData.overrides);
    } catch (_error) {
      console.error('Failed to load custom pricing data:', _error);
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateProfile = async (updates: Partial<CustomPricingProfile>) => {
    try {
      const response = await fetch(`/api/custom-pricing/profile/${userId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updates)
      });

      if (response.ok) {
        const data = await response.json();
        setProfile(data.profile);
        alert('Profile updated successfully!');
      }
    } catch (_error) {
      console.error('Failed to update profile:', _error);
      alert('Failed to update profile. Please try again.');
    }
  };

  const handleCreateEventOverride = async (eventId: string, overrideData: Partial<EventPricingOverride>) => {
    try {
      const response = await fetch('/api/custom-pricing/overrides', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          event_id: eventId,
          custom_pricing_profile_id: profile?.id,
          ...overrideData
        })
      });

      if (response.ok) {
        const data = await response.json();
        setEventOverrides([...eventOverrides, data.override]);
        setShowEventModal(false);
        setSelectedEvent(null);
        alert('Event pricing override created successfully!');
      }
    } catch (_error) {
      console.error('Failed to create event override:', _error);
      alert('Failed to create event override. Please try again.');
    }
  };

  const handleDeleteOverride = async (overrideId: string) => {
    if (!confirm('Are you sure you want to remove this pricing override?')) return;

    try {
      const response = await fetch(`/api/custom-pricing/overrides/${overrideId}`, {
        method: 'DELETE'
      });

      if (response.ok) {
        setEventOverrides(eventOverrides.filter(o => o.id !== overrideId));
        alert('Override removed successfully!');
      }
    } catch (_error) {
      console.error('Failed to delete override:', _error);
      alert('Failed to delete override. Please try again.');
    }
  };

  if (!isAdmin) {
    return (
      <div className="text-center py-12">
        <div className="text-6xl mb-4">🔒</div>
        <h3 className="text-lg font-medium text-gray-900 mb-2">Access Denied</h3>
        <p className="text-gray-600">This feature is only available to superusers.</p>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
      </div>
    );
  }

  return (
    <div className="max-w-6xl mx-auto p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 mb-2">Custom Pricing Management</h1>
        <p className="text-gray-600">Manage your custom pricing settings and event-specific overrides.</p>
      </div>

      {/* Tabs */}
      <div className="border-b border-gray-200 mb-6">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('profile')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'profile'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Profile Settings
          </button>
          <button
            onClick={() => setActiveTab('events')}
            className={`py-2 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'events'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Event Overrides
          </button>
        </nav>
      </div>

      {/* Profile Settings Tab */}
      {activeTab === 'profile' && (
        <div className="space-y-6">
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-lg font-medium mb-4">Stripe Account Settings</h2>
            
            <div className="space-y-4">
              <div>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={profile?.use_personal_stripe || false}
                    onChange={(e) => handleUpdateProfile({ use_personal_stripe: e.target.checked })}
                    className="mr-2"
                  />
                  Use Personal Stripe Account
                </label>
                <p className="text-sm text-gray-600 mt-1">
                  When enabled, payments will go directly to your personal Stripe account instead of the platform account.
                </p>
              </div>
              
              {profile?.use_personal_stripe && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Personal Stripe Account ID
                  </label>
                  <input
                    type="text"
                    value={profile?.stripe_account_id || ''}
                    onChange={(e) => handleUpdateProfile({ stripe_account_id: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="acct_xxxxxxxxxxxxx"
                  />
                  <p className="text-sm text-gray-600 mt-1">
                    Your Stripe Connect account ID. This can be found in your Stripe dashboard.
                  </p>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-lg font-medium mb-4">Platform Fee Settings</h2>
            
            <div className="space-y-4">
              <div>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={profile?.can_override_pricing || false}
                    onChange={(e) => handleUpdateProfile({ can_override_pricing: e.target.checked })}
                    className="mr-2"
                  />
                  Can Override Platform Fees
                </label>
              </div>
              
              <div>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={profile?.can_set_custom_fees || false}
                    onChange={(e) => handleUpdateProfile({ can_set_custom_fees: e.target.checked })}
                    className="mr-2"
                  />
                  Can Set Custom Fee Structure
                </label>
              </div>
              
              {profile?.can_set_custom_fees && (
                <div className="pl-6 space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Default Fee Type
                    </label>
                    <select
                      value={profile?.custom_platform_fee_type || 'percentage'}
                      onChange={(e) => handleUpdateProfile({ 
                        custom_platform_fee_type: e.target.value as 'percentage' | 'fixed' | 'none' 
                      })}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="percentage">Percentage</option>
                      <option value="fixed">Fixed Amount</option>
                      <option value="none">No Fees</option>
                    </select>
                  </div>
                  
                  {profile?.custom_platform_fee_type === 'percentage' && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Percentage (%)
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        min="0"
                        max="100"
                        value={profile?.custom_platform_fee_percentage || 0}
                        onChange={(e) => handleUpdateProfile({ 
                          custom_platform_fee_percentage: parseFloat(e.target.value) 
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  )}
                  
                  {profile?.custom_platform_fee_type === 'fixed' && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Fixed Amount (cents)
                      </label>
                      <input
                        type="number"
                        min="0"
                        value={profile?.custom_platform_fee_fixed || 0}
                        onChange={(e) => handleUpdateProfile({ 
                          custom_platform_fee_fixed: parseInt(e.target.value) 
                        })}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Event Overrides Tab */}
      {activeTab === 'events' && (
        <div className="space-y-6">
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-medium">Event-Specific Overrides</h2>
            <button
              onClick={() => setShowEventModal(true)}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
            >
              Add Override
            </button>
          </div>

          {eventOverrides.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-6xl mb-4">⚙️</div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">No Event Overrides</h3>
              <p className="text-gray-600 mb-4">Create event-specific pricing overrides to customize fees per event.</p>
              <button
                onClick={() => setShowEventModal(true)}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
              >
                Create First Override
              </button>
            </div>
          ) : (
            <div className="bg-white shadow rounded-lg overflow-hidden">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Event
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Custom Stripe
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Fee Override
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {eventOverrides.map((override) => {
                    const event = events.find(e => e.id === override.event_id);
                    return (
                      <tr key={override.id}>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div>
                            <div className="text-sm font-medium text-gray-900">
                              {event?.title || 'Unknown Event'}
                            </div>
                            <div className="text-sm text-gray-500">
                              {event?.organizations?.name}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                            override.use_custom_stripe_account
                              ? 'bg-green-100 text-green-800'
                              : 'bg-gray-100 text-gray-800'
                          }`}>
                            {override.use_custom_stripe_account ? 'Yes' : 'No'}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {override.override_platform_fees ? (
                            <div className="text-sm text-gray-900">
                              {override.platform_fee_type === 'percentage' && 
                                `${override.platform_fee_percentage}%`}
                              {override.platform_fee_type === 'fixed' && 
                                `$${(override.platform_fee_fixed || 0) / 100}`}
                              {override.platform_fee_type === 'none' && 'No Fees'}
                            </div>
                          ) : (
                            <span className="text-sm text-gray-500">Default</span>
                          )}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                          <button
                            onClick={() => handleDeleteOverride(override.id)}
                            className="text-red-600 hover:text-red-900"
                          >
                            Remove
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* Add Event Override Modal */}
      {showEventModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-2xl w-full p-6">
            <h2 className="text-xl font-bold mb-4">Add Event Override</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Select Event
                </label>
                <select
                  value={selectedEvent?.id || ''}
                  onChange={(e) => {
                    const event = events.find(ev => ev.id === e.target.value);
                    setSelectedEvent(event || null);
                  }}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">Choose an event...</option>
                  {events.filter(e => !eventOverrides.some(o => o.event_id === e.id)).map(event => (
                    <option key={event.id} value={event.id}>
                      {event.title} - {event.organizations.name}
                    </option>
                  ))}
                </select>
              </div>
              
              {selectedEvent && (
                <>
                  <div>
                    <label className="flex items-center">
                      <input type="checkbox" className="mr-2" />
                      Use Custom Stripe Account for this event
                    </label>
                  </div>
                  
                  <div>
                    <label className="flex items-center">
                      <input type="checkbox" className="mr-2" />
                      Override Platform Fees for this event
                    </label>
                  </div>
                </>
              )}
            </div>
            
            <div className="flex justify-end space-x-2 mt-6">
              <button
                onClick={() => {
                  setShowEventModal(false);
                  setSelectedEvent(null);
                }}
                className="px-4 py-2 text-gray-600 hover:text-gray-800 border border-gray-300 rounded-md hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (selectedEvent) {
                    handleCreateEventOverride(selectedEvent.id, {
                      use_custom_stripe_account: false,
                      override_platform_fees: false
                    });
                  }
                }}
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
              >
                Add Override
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default CustomPricingManager;