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 Promotion {
  id: string;
  name: string;
  description: string;
  type: 'early_bird' | 'flash_sale' | 'group_discount' | 'loyalty_reward' | 'referral';
  discount_percentage: number;
  start_date: string;
  end_date: string;
  max_uses: number;
  current_uses: number;
  is_active: boolean;
  conditions: any;
  created_at: string;
}

interface PromotionsTabProps {
  eventId: string;
}

export default function PromotionsTab({ eventId }: PromotionsTabProps) {
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editingPromotion, setEditingPromotion] = useState<Promotion | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    type: 'early_bird' as const,
    discount_percentage: 10,
    start_date: '',
    end_date: '',
    max_uses: 100,
    conditions: {}
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

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

  const loadPromotions = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('promotions')
        .select('*')
        .eq('event_id', eventId)
        .order('created_at', { ascending: false });

      if (error) throw error;
      setPromotions(data || []);
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handleCreatePromotion = () => {
    setEditingPromotion(null);
    setFormData({
      name: '',
      description: '',
      type: 'early_bird',
      discount_percentage: 10,
      start_date: new Date().toISOString().split('T')[0],
      end_date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      max_uses: 100,
      conditions: {}
    });
    setShowModal(true);
  };

  const handleEditPromotion = (promotion: Promotion) => {
    setEditingPromotion(promotion);
    setFormData({
      name: promotion.name,
      description: promotion.description,
      type: promotion.type,
      discount_percentage: promotion.discount_percentage,
      start_date: promotion.start_date.split('T')[0],
      end_date: promotion.end_date.split('T')[0],
      max_uses: promotion.max_uses,
      conditions: promotion.conditions || {}
    });
    setShowModal(true);
  };

  const handleSavePromotion = async () => {
    setSaving(true);
    try {
      const promotionData = {
        ...formData,
        event_id: eventId,
        start_date: new Date(formData.start_date).toISOString(),
        end_date: new Date(formData.end_date).toISOString()
      };

      if (editingPromotion) {
        const { error } = await supabase
          .from('promotions')
          .update(promotionData)
          .eq('id', editingPromotion.id);

        if (error) throw error;
      } else {
        const { error } = await supabase
          .from('promotions')
          .insert({
            ...promotionData,
            is_active: true,
            current_uses: 0
          });

        if (error) throw error;
      }

      setShowModal(false);
      loadPromotions();
    } catch (error) {

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

  const handleDeletePromotion = async (promotion: Promotion) => {
    if (confirm(`Are you sure you want to delete "${promotion.name}"?`)) {
      try {
        const { error } = await supabase
          .from('promotions')
          .delete()
          .eq('id', promotion.id);

        if (error) throw error;
        loadPromotions();
      } catch (error) {

        alert('Failed to delete promotion');
      }
    }
  };

  const handleTogglePromotion = async (promotion: Promotion) => {
    try {
      const { error } = await supabase
        .from('promotions')
        .update({ is_active: !promotion.is_active })
        .eq('id', promotion.id);

      if (error) throw error;
      loadPromotions();
    } catch (error) {

      alert('Failed to toggle promotion');
    }
  };

  const getPromotionIcon = (type: string) => {
    switch (type) {
      case 'early_bird':
        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 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        );
      case 'flash_sale':
        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>
        );
      case 'group_discount':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
          </svg>
        );
      case 'loyalty_reward':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z" />
          </svg>
        );
      case 'referral':
        return (
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
          </svg>
        );
      default:
        return null;
    }
  };

  const getPromotionColor = (type: string) => {
    switch (type) {
      case 'early_bird':
        return 'text-blue-400 bg-blue-500/20';
      case 'flash_sale':
        return 'text-red-400 bg-red-500/20';
      case 'group_discount':
        return 'text-green-400 bg-green-500/20';
      case 'loyalty_reward':
        return 'text-yellow-400 bg-yellow-500/20';
      case 'referral':
        return 'text-purple-400 bg-purple-500/20';
      default:
        return 'text-white/60 bg-white/10';
    }
  };

  const isPromotionActive = (promotion: Promotion) => {
    const now = new Date();
    const start = new Date(promotion.start_date);
    const end = new Date(promotion.end_date);
    return promotion.is_active && now >= start && now <= end;
  };

  const getPromotionStats = () => {
    const total = promotions.length;
    const active = promotions.filter(p => isPromotionActive(p)).length;
    const scheduled = promotions.filter(p => p.is_active && new Date(p.start_date) > new Date()).length;
    const expired = promotions.filter(p => new Date(p.end_date) < new Date()).length;
    
    return { total, active, scheduled, expired };
  };

  const stats = getPromotionStats();

  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">Promotions & Campaigns</h2>
        <button
          onClick={handleCreatePromotion}
          className="flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all duration-200"
          style={{
            background: 'var(--glass-text-accent)',
            color: 'white'
          }}
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
          </svg>
          Create Promotion
        </button>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Total Promotions</div>
          <div className="text-2xl font-bold text-white">{stats.total}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Active</div>
          <div className="text-2xl font-bold text-green-400">{stats.active}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Scheduled</div>
          <div className="text-2xl font-bold text-blue-400">{stats.scheduled}</div>
        </div>
        <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-xl p-4">
          <div className="text-sm text-white/60">Expired</div>
          <div className="text-2xl font-bold text-gray-400">{stats.expired}</div>
        </div>
      </div>

      {/* Promotions Grid */}
      {promotions.length === 0 ? (
        <div className="text-center py-12">
          <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="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
          </svg>
          <p className="text-white/60 mb-4">No promotions created yet</p>
          <button
            onClick={handleCreatePromotion}
            className="px-6 py-3 rounded-lg font-medium transition-all duration-200"
            style={{
              background: 'var(--glass-text-accent)',
              color: 'white'
            }}
          >
            Create Your First Promotion
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {promotions.map((promotion) => (
            <div key={promotion.id} className="bg-white/5 border border-white/20 rounded-xl p-6 hover:bg-white/10 transition-all duration-200">
              <div className="flex justify-between items-start mb-4">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <div className={`p-2 rounded-lg ${getPromotionColor(promotion.type)}`}>
                      {getPromotionIcon(promotion.type)}
                    </div>
                    <div>
                      <h3 className="text-xl font-semibold text-white">{promotion.name}</h3>
                      <div className="text-sm text-white/60 capitalize">{promotion.type.replace('_', ' ')}</div>
                    </div>
                  </div>
                  {promotion.description && (
                    <p className="text-white/70 text-sm mb-3">{promotion.description}</p>
                  )}
                  <div className="text-3xl font-bold text-purple-400 mb-2">
                    {promotion.discount_percentage}% OFF
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleEditPromotion(promotion)}
                    className="p-2 text-white/60 hover:text-white transition-colors"
                    title="Edit"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                  </button>
                  <button
                    onClick={() => handleTogglePromotion(promotion)}
                    className="p-2 text-white/60 hover:text-white transition-colors"
                    title={promotion.is_active ? 'Deactivate' : 'Activate'}
                  >
                    {promotion.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={() => handleDeletePromotion(promotion)}
                    className="p-2 text-white/60 hover:text-red-400 transition-colors"
                    title="Delete"
                  >
                    <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 className="space-y-3">
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div>
                    <div className="text-white/60">Status</div>
                    <div className={`font-semibold ${
                      isPromotionActive(promotion) ? 'text-green-400' :
                      new Date(promotion.start_date) > new Date() ? 'text-blue-400' :
                      'text-gray-400'
                    }`}>
                      {isPromotionActive(promotion) ? 'Active' :
                       new Date(promotion.start_date) > new Date() ? 'Scheduled' :
                       'Expired'}
                    </div>
                  </div>
                  <div>
                    <div className="text-white/60">Usage</div>
                    <div className="text-white font-semibold">
                      {promotion.current_uses} / {promotion.max_uses}
                    </div>
                  </div>
                  <div>
                    <div className="text-white/60">Ends</div>
                    <div className="text-white font-semibold">
                      {new Date(promotion.end_date).toLocaleDateString()}
                    </div>
                  </div>
                </div>

                <div className="w-full bg-white/10 rounded-full h-2">
                  <div 
                    className="bg-gradient-to-r from-purple-500 to-pink-500 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${(promotion.current_uses / promotion.max_uses) * 100}%` }}
                  />
                </div>
                <div className="text-xs text-white/60">
                  {((promotion.current_uses / promotion.max_uses) * 100).toFixed(1)}% used
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-2xl max-w-lg w-full">
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-light text-white">
                  {editingPromotion ? 'Edit Promotion' : 'Create Promotion'}
                </h3>
                <button
                  onClick={() => setShowModal(false)}
                  className="text-white/60 hover:text-white transition-colors"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Name</label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:border-transparent"
                    style={{
                      '--tw-ring-color': 'var(--glass-text-accent)'
                    } as React.CSSProperties}
                    placeholder="Early Bird Special"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Description</label>
                  <textarea
                    value={formData.description}
                    onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                    rows={3}
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                    placeholder="Limited time offer for early purchasers..."
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-white/80 mb-2">Type</label>
                    <select
                      value={formData.type}
                      onChange={(e) => setFormData(prev => ({ ...prev, type: e.target.value as any }))}
                      className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:border-transparent"
                      style={{
                        '--tw-ring-color': 'var(--glass-text-accent)'
                      } as React.CSSProperties}
                    >
                      <option value="early_bird">Early Bird</option>
                      <option value="flash_sale">Flash Sale</option>
                      <option value="group_discount">Group Discount</option>
                      <option value="loyalty_reward">Loyalty Reward</option>
                      <option value="referral">Referral</option>
                    </select>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-white/80 mb-2">Discount (%)</label>
                    <input
                      type="number"
                      value={formData.discount_percentage}
                      onChange={(e) => setFormData(prev => ({ ...prev, discount_percentage: parseInt(e.target.value) || 0 }))}
                      className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:border-transparent"
                    style={{
                      '--tw-ring-color': 'var(--glass-text-accent)'
                    } as React.CSSProperties}
                      min="1"
                      max="100"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-white/80 mb-2">Start Date</label>
                    <input
                      type="date"
                      value={formData.start_date}
                      onChange={(e) => setFormData(prev => ({ ...prev, start_date: e.target.value }))}
                      className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:border-transparent"
                      style={{
                        '--tw-ring-color': 'var(--glass-text-accent)'
                      } as React.CSSProperties}
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-white/80 mb-2">End Date</label>
                    <input
                      type="date"
                      value={formData.end_date}
                      onChange={(e) => setFormData(prev => ({ ...prev, end_date: e.target.value }))}
                      className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:border-transparent"
                      style={{
                        '--tw-ring-color': 'var(--glass-text-accent)'
                      } as React.CSSProperties}
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/80 mb-2">Max Uses</label>
                  <input
                    type="number"
                    value={formData.max_uses}
                    onChange={(e) => setFormData(prev => ({ ...prev, max_uses: parseInt(e.target.value) || 0 }))}
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:border-transparent"
                    style={{
                      '--tw-ring-color': 'var(--glass-text-accent)'
                    } as React.CSSProperties}
                    min="1"
                  />
                </div>
              </div>

              <div className="flex justify-end space-x-3 mt-6">
                <button
                  onClick={() => setShowModal(false)}
                  className="px-6 py-3 text-white/80 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSavePromotion}
                  disabled={saving}
                  className="px-6 py-3 rounded-lg font-medium transition-all duration-200 disabled:opacity-50"
                  style={{
                    background: 'var(--glass-text-accent)',
                    color: 'white'
                  }}
                >
                  {saving ? 'Saving...' : editingPromotion ? 'Update' : 'Create'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}