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

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

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

export default function SettingsTab({ eventId, organizationId }: SettingsTabProps) {
  const [eventData, setEventData] = useState<any>(null);
  const [availabilitySettings, setAvailabilitySettings] = useState({
    show_remaining_tickets: true,
    show_sold_out_message: true,
    hide_event_after_sold_out: false,
    sales_start_date: '',
    sales_end_date: '',
    auto_close_sales: false,
    require_phone_number: false,
    require_address: false,
    custom_fields: [] as Array<{
      id: string;
      label: string;
      type: 'text' | 'select' | 'checkbox';
      required: boolean;
      options?: string[];
    }>
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

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

  const loadData = async () => {
    setLoading(true);
    try {
      const event = await loadEventData(eventId, organizationId);
      if (event) {
        setEventData(event);
        
        // Load availability settings
        const settings = event.availability_settings || {};
        setAvailabilitySettings({
          show_remaining_tickets: settings.show_remaining_tickets ?? true,
          show_sold_out_message: settings.show_sold_out_message ?? true,
          hide_event_after_sold_out: settings.hide_event_after_sold_out ?? false,
          sales_start_date: settings.sales_start_date || '',
          sales_end_date: settings.sales_end_date || '',
          auto_close_sales: settings.auto_close_sales ?? false,
          require_phone_number: settings.require_phone_number ?? false,
          require_address: settings.require_address ?? false,
          custom_fields: settings.custom_fields || []
        });
      }
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handleSaveSettings = async () => {
    setSaving(true);
    try {
      const success = await updateEventData(eventId, {
        availability_settings: availabilitySettings
      });
      
      if (success) {
        alert('Settings saved successfully!');
      } else {
        alert('Failed to save settings');
      }
    } catch (error) {

      alert('Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const addCustomField = () => {
    const newField = {
      id: Date.now().toString(),
      label: '',
      type: 'text' as const,
      required: false,
      options: []
    };
    setAvailabilitySettings(prev => ({
      ...prev,
      custom_fields: [...prev.custom_fields, newField]
    }));
  };

  const updateCustomField = (id: string, updates: Partial<typeof availabilitySettings.custom_fields[0]>) => {
    setAvailabilitySettings(prev => ({
      ...prev,
      custom_fields: prev.custom_fields.map(field => 
        field.id === id ? { ...field, ...updates } : field
      )
    }));
  };

  const removeCustomField = (id: string) => {
    setAvailabilitySettings(prev => ({
      ...prev,
      custom_fields: prev.custom_fields.filter(field => field.id !== id)
    }));
  };

  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">Event Settings</h2>
        <button
          onClick={handleSaveSettings}
          disabled={saving}
          className="px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 text-white rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
        >
          {saving ? 'Saving...' : 'Save Settings'}
        </button>
      </div>

      <div className="space-y-8">
        {/* Ticket Availability Display */}
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4">Ticket Availability Display</h3>
          <div className="space-y-4">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.show_remaining_tickets}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, show_remaining_tickets: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Show remaining ticket count</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.show_sold_out_message}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, show_sold_out_message: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Show "sold out" message when tickets are unavailable</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.hide_event_after_sold_out}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, hide_event_after_sold_out: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Hide event completely when sold out</span>
            </label>
          </div>
        </div>

        {/* Sales Schedule */}
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4">Sales Schedule</h3>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-white/80 mb-2">Sales Start Date</label>
                <input
                  type="datetime-local"
                  value={availabilitySettings.sales_start_date}
                  onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, sales_start_date: e.target.value }))}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="text-xs text-white/60 mt-1">Leave empty to start sales immediately</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-2">Sales End Date</label>
                <input
                  type="datetime-local"
                  value={availabilitySettings.sales_end_date}
                  onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, sales_end_date: e.target.value }))}
                  className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="text-xs text-white/60 mt-1">Leave empty to continue sales until event date</p>
              </div>
            </div>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.auto_close_sales}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, auto_close_sales: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Automatically close sales 1 hour before event</span>
            </label>
          </div>
        </div>

        {/* Customer Information Requirements */}
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4">Customer Information Requirements</h3>
          <div className="space-y-4">
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.require_phone_number}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, require_phone_number: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Require phone number</span>
            </label>
            <label className="flex items-center">
              <input
                type="checkbox"
                checked={availabilitySettings.require_address}
                onChange={(e) => setAvailabilitySettings(prev => ({ ...prev, require_address: e.target.checked }))}
                className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
              />
              <span className="ml-2 text-white">Require address</span>
            </label>
          </div>
        </div>

        {/* Custom Fields */}
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <div className="flex justify-between items-center mb-4">
            <h3 className="text-lg font-semibold text-white">Custom Fields</h3>
            <button
              onClick={addCustomField}
              className="px-3 py-1 rounded-lg text-sm transition-all duration-200 hover:shadow-lg hover:scale-105"
              style={{
                background: 'var(--glass-text-accent)',
                color: 'white'
              }}
            >
              Add Field
            </button>
          </div>
          
          {availabilitySettings.custom_fields.length === 0 ? (
            <p className="text-white/60">No custom fields configured</p>
          ) : (
            <div className="space-y-4">
              {availabilitySettings.custom_fields.map((field) => (
                <div key={field.id} className="bg-white/5 border border-white/10 rounded-lg p-4">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-white/80 mb-1">Label</label>
                      <input
                        type="text"
                        value={field.label}
                        onChange={(e) => updateCustomField(field.id, { label: e.target.value })}
                        className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        placeholder="Field label"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-white/80 mb-1">Type</label>
                      <select
                        value={field.type}
                        onChange={(e) => updateCustomField(field.id, { type: e.target.value as any })}
                        className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      >
                        <option value="text">Text</option>
                        <option value="select">Select</option>
                        <option value="checkbox">Checkbox</option>
                      </select>
                    </div>
                    <div className="flex items-end gap-2">
                      <label className="flex items-center">
                        <input
                          type="checkbox"
                          checked={field.required}
                          onChange={(e) => updateCustomField(field.id, { required: e.target.checked })}
                          className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
                        />
                        <span className="ml-2 text-white text-sm">Required</span>
                      </label>
                      <button
                        onClick={() => removeCustomField(field.id)}
                        className="p-2 text-white/60 hover:text-red-400 transition-colors"
                        title="Remove field"
                      >
                        <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>
                  
                  {field.type === 'select' && (
                    <div className="mt-3">
                      <label className="block text-sm font-medium text-white/80 mb-1">Options (one per line)</label>
                      <textarea
                        value={field.options?.join('\n') || ''}
                        onChange={(e) => updateCustomField(field.id, { options: e.target.value.split('\n').filter(o => o.trim()) })}
                        rows={3}
                        className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                        placeholder="Option 1&#10;Option 2&#10;Option 3"
                      />
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Preview Section */}
        <div className="bg-white/5 border border-white/20 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4">Checkout Form Preview</h3>
          <div className="bg-white/10 rounded-lg p-4 border border-white/10">
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">Name *</label>
                  <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                    John Doe
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">Email *</label>
                  <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                    john@example.com
                  </div>
                </div>
              </div>
              
              {availabilitySettings.require_phone_number && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">Phone Number *</label>
                  <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                    (555) 123-4567
                  </div>
                </div>
              )}
              
              {availabilitySettings.require_address && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">Address *</label>
                  <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                    123 Main St, City, State 12345
                  </div>
                </div>
              )}
              
              {availabilitySettings.custom_fields.map((field) => (
                <div key={field.id}>
                  <label className="block text-sm font-medium text-white/80 mb-1">
                    {field.label} {field.required && '*'}
                  </label>
                  {field.type === 'text' && (
                    <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                      Sample text input
                    </div>
                  )}
                  {field.type === 'select' && (
                    <div className="w-full px-3 py-2 bg-white/20 border border-white/30 rounded-lg text-white/60 text-sm">
                      {field.options?.[0] || 'Select an option'}
                    </div>
                  )}
                  {field.type === 'checkbox' && (
                    <label className="flex items-center">
                      <input
                        type="checkbox"
                        className="w-4 h-4 text-blue-600 bg-white/10 border-white/20 rounded focus:ring-blue-500"
                        disabled
                      />
                      <span className="ml-2 text-white/60 text-sm">{field.label}</span>
                    </label>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}