import { useState, useEffect } from 'react';
import { createClient } from '@supabase/supabase-js';
import { formatCurrency } from '../../lib/event-management';

const supabase = createClient(
  import.meta.env.PUBLIC_SUPABASE_URL,
  import.meta.env.PUBLIC_SUPABASE_ANON_KEY
);

interface Addon {
  id: string;
  name: string;
  description: string;
  price_cents: number;
  category: string;
  is_active: boolean;
  organization_id: string;
}

interface EventAddon {
  id: string;
  event_id: string;
  addon_id: string;
  is_active: boolean;
  addons: Addon;
}

interface AddonsTabProps {
  eventId: string;
  organizationId: string;
}

export default function AddonsTab({ eventId, organizationId }: AddonsTabProps) {
  const [availableAddons, setAvailableAddons] = useState<Addon[]>([]);
  const [eventAddons, setEventAddons] = useState<EventAddon[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, [eventId, organizationId]);

  const loadData = async () => {
    setLoading(true);
    try {
      // Load available addons for the organization
      const { data: addonsData, error: addonsError } = await supabase
        .from('addons')
        .select('*')
        .eq('organization_id', organizationId)
        .eq('is_active', true)
        .order('category', { ascending: true });

      if (addonsError) throw addonsError;

      // Load event-specific addons
      const { data: eventAddonsData, error: eventAddonsError } = await supabase
        .from('event_addons')
        .select(`
          id,
          event_id,
          addon_id,
          is_active,
          addons (
            id,
            name,
            description,
            price_cents,
            category,
            is_active,
            organization_id
          )
        `)
        .eq('event_id', eventId);

      if (eventAddonsError) throw eventAddonsError;

      setAvailableAddons(addonsData || []);
      setEventAddons(eventAddonsData || []);
    } catch (_error) {
      // Handle error silently
    } finally {
      setLoading(false);
    }
  };

  const handleAddAddon = async (addon: Addon) => {
    try {
      const { data, error } = await supabase
        .from('event_addons')
        .insert({
          event_id: eventId,
          addon_id: addon.id,
          is_active: true
        })
        .select(`
          id,
          event_id,
          addon_id,
          is_active,
          addons (
            id,
            name,
            description,
            price_cents,
            category,
            is_active,
            organization_id
          )
        `)
        .single();

      if (error) throw error;

      setEventAddons(prev => [...prev, data]);
    } catch (_error) {
      // Handle error silently
    }
  };

  const handleRemoveAddon = async (eventAddon: EventAddon) => {
    try {
      const { error } = await supabase
        .from('event_addons')
        .delete()
        .eq('id', eventAddon.id);

      if (error) throw error;

      setEventAddons(prev => prev.filter(ea => ea.id !== eventAddon.id));
    } catch (_error) {
      // Handle error silently
    }
  };

  const handleToggleAddon = async (eventAddon: EventAddon) => {
    try {
      const { error } = await supabase
        .from('event_addons')
        .update({ is_active: !eventAddon.is_active })
        .eq('id', eventAddon.id);

      if (error) throw error;

      setEventAddons(prev => prev.map(ea => 
        ea.id === eventAddon.id ? { ...ea, is_active: !ea.is_active } : ea
      ));
    } catch (_error) {
      // Handle error silently
    }
  };

  const getCategoryIcon = (category: string) => {
    switch (category.toLowerCase()) {
      case 'merchandise':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
          </svg>
        );
      case 'food':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
          </svg>
        );
      case 'drink':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
          </svg>
        );
      case 'service':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
        );
      default:
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
        );
    }
  };

  const groupByCategory = (addons: Addon[]) => {
    return addons.reduce((acc, addon) => {
      const category = addon.category || 'Other';
      if (!acc[category]) acc[category] = [];
      acc[category].push(addon);
      return acc;
    }, {} as Record<string, Addon[]>);
  };

  const isAddonAdded = (addon: Addon) => {
    return eventAddons.some(ea => ea.addon_id === addon.id);
  };

  const getEventAddon = (addon: Addon) => {
    return eventAddons.find(ea => ea.addon_id === addon.id);
  };

  const groupedAvailableAddons = groupByCategory(availableAddons);
  const groupedEventAddons = groupByCategory(eventAddons.map(ea => ea.addons));

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

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-light text-white">Add-ons & Extras</h2>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        {/* Current Add-ons */}
        <div>
          <h3 className="text-xl font-semibold text-white mb-4">Current Add-ons</h3>
          
          {eventAddons.length === 0 ? (
            <div className="bg-white/5 border border-white/20 rounded-xl p-8 text-center">
              <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
              </svg>
              <p className="text-white/60">No add-ons added to this event yet</p>
              <p className="text-white/40 text-sm mt-2">Select from available add-ons to get started</p>
            </div>
          ) : (
            <div className="space-y-4">
              {Object.entries(groupedEventAddons).map(([category, addons]) => (
                <div key={category} className="bg-white/5 border border-white/20 rounded-xl p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <div className="text-blue-400">
                      {getCategoryIcon(category)}
                    </div>
                    <h4 className="text-lg font-semibold text-white">{category}</h4>
                  </div>
                  
                  <div className="space-y-3">
                    {addons.map((addon) => {
                      const eventAddon = getEventAddon(addon);
                      return (
                        <div key={addon.id} className="flex items-center justify-between p-3 bg-white/5 border border-white/10 rounded-lg">
                          <div className="flex-1">
                            <div className="flex items-center gap-3">
                              <div className="text-white font-medium">{addon.name}</div>
                              <span className={`px-2 py-1 text-xs rounded-full ${
                                eventAddon?.is_active
                                  ? 'bg-green-500/20 text-green-300 border border-green-500/30'
                                  : 'bg-red-500/20 text-red-300 border border-red-500/30'
                              }`}>
                                {eventAddon?.is_active ? 'Active' : 'Inactive'}
                              </span>
                            </div>
                            {addon.description && (
                              <div className="text-white/60 text-sm mt-1">{addon.description}</div>
                            )}
                          </div>
                          <div className="flex items-center gap-3">
                            <div className="text-white font-bold">{formatCurrency(addon.price_cents)}</div>
                            <div className="flex items-center gap-1">
                              <button
                                onClick={() => eventAddon && handleToggleAddon(eventAddon)}
                                className="p-2 text-white/60 hover:text-white transition-colors"
                                title={eventAddon?.is_active ? 'Deactivate' : 'Activate'}
                              >
                                {eventAddon?.is_active ? (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.142 4.142M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
                                  </svg>
                                ) : (
                                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                  </svg>
                                )}
                              </button>
                              <button
                                onClick={() => eventAddon && handleRemoveAddon(eventAddon)}
                                className="p-2 text-white/60 hover:text-red-400 transition-colors"
                                title="Remove"
                              >
                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                </svg>
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Available Add-ons */}
        <div>
          <h3 className="text-xl font-semibold text-white mb-4">Available Add-ons</h3>
          
          {availableAddons.length === 0 ? (
            <div className="bg-white/5 border border-white/20 rounded-xl p-8 text-center">
              <svg className="w-12 h-12 text-white/40 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
              </svg>
              <p className="text-white/60">No add-ons available</p>
              <p className="text-white/40 text-sm mt-2">Create add-ons in your organization settings</p>
            </div>
          ) : (
            <div className="space-y-4">
              {Object.entries(groupedAvailableAddons).map(([category, addons]) => (
                <div key={category} className="bg-white/5 border border-white/20 rounded-xl p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <div className="text-purple-400">
                      {getCategoryIcon(category)}
                    </div>
                    <h4 className="text-lg font-semibold text-white">{category}</h4>
                  </div>
                  
                  <div className="space-y-3">
                    {addons.map((addon) => (
                      <div key={addon.id} className="flex items-center justify-between p-3 bg-white/5 border border-white/10 rounded-lg">
                        <div className="flex-1">
                          <div className="text-white font-medium">{addon.name}</div>
                          {addon.description && (
                            <div className="text-white/60 text-sm mt-1">{addon.description}</div>
                          )}
                        </div>
                        <div className="flex items-center gap-3">
                          <div className="text-white font-bold">{formatCurrency(addon.price_cents)}</div>
                          {isAddonAdded(addon) ? (
                            <span className="px-3 py-1 bg-green-500/20 text-green-300 border border-green-500/30 rounded-lg text-sm">
                              Added
                            </span>
                          ) : (
                            <button
                              onClick={() => handleAddAddon(addon)}
                              className="px-3 py-1 text-white rounded-lg text-sm transition-colors"
                              style={{
                                background: 'var(--glass-text-accent)'
                              }}
                            >
                              Add
                            </button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}