import { useState, useEffect } from 'react';
import { loadTicketTypes, deleteTicketType, toggleTicketTypeStatus } from '../../lib/ticket-management';
import { loadSalesData, calculateSalesMetrics } from '../../lib/sales-analytics';
import { formatCurrency } from '../../lib/event-management';
import TicketTypeModal from '../modals/TicketTypeModal';
import type { TicketType } from '../../lib/ticket-management';

interface TicketsTabProps {
  eventId: string;
}

export default function TicketsTab({ eventId }: TicketsTabProps) {
  const [ticketTypes, setTicketTypes] = useState<TicketType[]>([]);
  const [salesData, setSalesData] = useState<any[]>([]);
  const [viewMode, setViewMode] = useState<'card' | 'list'>('card');
  const [showModal, setShowModal] = useState(false);
  const [editingTicketType, setEditingTicketType] = useState<TicketType | undefined>();
  const [loading, setLoading] = useState(true);

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

  const loadData = async () => {
    setLoading(true);
    try {
      const [ticketTypesData, salesDataResult] = await Promise.all([
        loadTicketTypes(eventId),
        loadSalesData(eventId)
      ]);
      
      setTicketTypes(ticketTypesData);
      setSalesData(salesDataResult);
    } catch (error) {

    } finally {
      setLoading(false);
    }
  };

  const handleCreateTicketType = () => {
    setEditingTicketType(undefined);
    setShowModal(true);
  };

  const handleEditTicketType = (ticketType: TicketType) => {
    setEditingTicketType(ticketType);
    setShowModal(true);
  };

  const handleDeleteTicketType = async (ticketTypeId: string) => {
    if (!confirm('Are you sure you want to delete this ticket type? This action cannot be undone.')) {
      return;
    }

    try {
      await deleteTicketType(ticketTypeId);
      await loadData();
    } catch (error) {

    }
  };

  const handleToggleStatus = async (ticketType: TicketType) => {
    try {
      await toggleTicketTypeStatus(ticketType.id, !ticketType.is_active);
      await loadData();
    } catch (error) {

    }
  };

  const getSalesStats = (ticketTypeId: string) => {
    const salesMetrics = calculateSalesMetrics(salesData.filter(sale => sale.ticket_type_id === ticketTypeId));
    return {
      sold: salesMetrics.totalTickets,
      revenue: salesMetrics.totalRevenue,
      available: ticketTypes.find(tt => tt.id === ticketTypeId)?.available || 0
    };
  };

  const renderTicketCard = (ticketType: TicketType) => {
    const stats = getSalesStats(ticketType.id);
    const percentage = ticketType.quantity > 0 
      ? (stats.sold / ticketType.quantity) * 100 
      : 0;

    const isActive = ticketType.is_active && ticketType.sale_start <= new Date() && 
                    (!ticketType.sale_end || ticketType.sale_end >= new Date());

    return (
      <div 
        key={ticketType.id} 
        className="rounded-xl p-6 transition-all duration-200 glass-card hover:shadow-lg"
      >
        <div className="flex justify-between items-start mb-4">
          <div className="flex-1">
            <div className="flex items-center gap-3 mb-2">
              <h3 className="text-xl font-semibold" style={{ color: 'var(--glass-text-primary)' }}>
                {ticketType.name}
              </h3>
              <span 
                className={`px-2 py-1 text-xs font-medium rounded-full ${
                  isActive ? 'premium-success' : 'premium-error'
                }`}
              >
                {isActive ? 'Active' : 'Inactive'}
              </span>
            </div>
            {ticketType.description && (
              <p className="text-sm mb-3" style={{ color: 'var(--glass-text-secondary)' }}>
                {ticketType.description}
              </p>
            )}
          </div>
          <div className="text-2xl font-bold mb-2" style={{ color: 'var(--glass-text-primary)' }}>
            {formatCurrency(ticketType.price)}
            {ticketType.fees_included && <span className="text-sm font-normal" style={{ color: 'var(--glass-text-tertiary)' }}> (fees included)</span>}
          </div>
        </div>

        <div className="flex gap-2 mb-4">
          <button
            onClick={() => handleEditTicketType(ticketType)}
            className="p-2 transition-colors hover:opacity-80"
            style={{ color: 'var(--glass-text-tertiary)' }}
          >
            <svg className="w-5 h-5" 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={() => handleToggleStatus(ticketType)}
            className="p-2 transition-colors hover:opacity-80"
            style={{ color: 'var(--glass-text-tertiary)' }}
          >
            {ticketType.is_active ? (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            ) : (
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            )}
          </button>
          <button
            onClick={() => handleDeleteTicketType(ticketType.id)}
            className="p-2 transition-colors hover:opacity-80"
            style={{ color: 'var(--error-color)' }}
          >
            <svg className="w-5 h-5" 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 className="grid grid-cols-3 gap-4 mb-4">
          <div className="text-center">
            <div style={{ color: 'var(--glass-text-tertiary)' }}>Sold</div>
            <div className="font-semibold" style={{ color: 'var(--glass-text-primary)' }}>{stats.sold}</div>
          </div>
          <div className="text-center">
            <div style={{ color: 'var(--glass-text-tertiary)' }}>Available</div>
            <div className="font-semibold" style={{ color: 'var(--glass-text-primary)' }}>{stats.available}</div>
          </div>
          <div className="text-center">
            <div style={{ color: 'var(--glass-text-tertiary)' }}>Revenue</div>
            <div className="font-semibold" style={{ color: 'var(--glass-text-primary)' }}>{formatCurrency(stats.revenue)}</div>
          </div>
        </div>
        
        <div className="space-y-2">
          <div className="w-full rounded-full h-2" style={{ background: 'var(--glass-bg)' }}>
            <div 
              className="h-2 rounded-full bg-gradient-to-r from-blue-600 to-purple-600"
              style={{ width: `${Math.min(percentage, 100)}%` }}
            />
          </div>
          <div className="text-xs" style={{ color: 'var(--glass-text-tertiary)' }}>
            {percentage.toFixed(1)}% sold ({stats.sold} of {ticketType.quantity})
          </div>
        </div>
      </div>
    );
  };

  const renderTicketRow = (ticketType: TicketType) => {
    const stats = getSalesStats(ticketType.id);
    const percentage = ticketType.quantity > 0 
      ? (stats.sold / ticketType.quantity) * 100 
      : 0;

    const isActive = ticketType.is_active && ticketType.sale_start <= new Date() && 
                    (!ticketType.sale_end || ticketType.sale_end >= new Date());

    return (
      <tr key={ticketType.id} className="border-b transition-colors hover:opacity-90" style={{ borderColor: 'var(--glass-border)' }}>
        <td className="py-4 px-4">
          <div>
            <div className="font-semibold" style={{ color: 'var(--glass-text-primary)' }}>{ticketType.name}</div>
            {ticketType.description && (
              <div className="text-sm" style={{ color: 'var(--glass-text-secondary)' }}>{ticketType.description}</div>
            )}
            <span 
              className={`inline-block mt-1 px-2 py-1 text-xs font-medium rounded-full ${
                isActive ? 'premium-success' : 'premium-error'
              }`}
            >
              {isActive ? 'Active' : 'Inactive'}
            </span>
          </div>
        </td>
        <td className="py-4 px-4 font-semibold" style={{ color: 'var(--glass-text-primary)' }}>
          {formatCurrency(ticketType.price)}
        </td>
        <td className="py-4 px-4" style={{ color: 'var(--glass-text-primary)' }}>{stats.sold}</td>
        <td className="py-4 px-4" style={{ color: 'var(--glass-text-primary)' }}>{stats.available}</td>
        <td className="py-4 px-4 font-semibold" style={{ color: 'var(--glass-text-primary)' }}>
          {formatCurrency(stats.revenue)}
        </td>
        <td className="py-4 px-4">
          <div className="flex items-center gap-2">
            <div className="w-20 rounded-full h-2" style={{ background: 'var(--glass-bg)' }}>
              <div 
                className="h-2 rounded-full bg-gradient-to-r from-blue-600 to-purple-600"
                style={{ width: `${Math.min(percentage, 100)}%` }}
              />
            </div>
            <span className="text-sm" style={{ color: 'var(--glass-text-tertiary)' }}>{percentage.toFixed(1)}%</span>
          </div>
        </td>
        <td className="py-4 px-4">
          <div className="flex gap-2">
            <button
              onClick={() => handleEditTicketType(ticketType)}
              className="p-2 transition-colors hover:opacity-80"
              style={{ color: 'var(--glass-text-tertiary)' }}
            >
              <svg className="w-5 h-5" 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={() => handleToggleStatus(ticketType)}
              className="p-2 transition-colors hover:opacity-80"
              style={{ color: 'var(--glass-text-tertiary)' }}
            >
              {ticketType.is_active ? (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              ) : (
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              )}
            </button>
            <button
              onClick={() => handleDeleteTicketType(ticketType.id)}
              className="p-2 transition-colors hover:opacity-80"
              style={{ color: 'var(--error-color)' }}
            >
              <svg className="w-5 h-5" 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>
        </td>
      </tr>
    );
  };

  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" style={{ borderColor: 'var(--glass-text-primary)' }}></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-2xl font-light" style={{ color: 'var(--glass-text-primary)' }}>Ticket Types & Pricing</h2>
        <div className="flex items-center gap-3">
          <div className="flex items-center rounded-lg p-1" style={{ background: 'var(--glass-bg)' }}>
            <button
              onClick={() => setViewMode('card')}
              className={`px-3 py-1.5 rounded-md transition-all ${
                viewMode === 'card' 
                  ? '' 
                  : ''
              }`}
              style={{
                background: viewMode === 'card' ? 'var(--glass-bg-lg)' : 'transparent',
                color: viewMode === 'card' ? 'var(--glass-text-primary)' : 'var(--glass-text-tertiary)'
              }}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" />
              </svg>
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`px-3 py-1.5 rounded-md transition-all ${
                viewMode === 'list' 
                  ? '' 
                  : ''
              }`}
              style={{
                background: viewMode === 'list' ? 'var(--glass-bg-lg)' : 'transparent',
                color: viewMode === 'list' ? 'var(--glass-text-primary)' : 'var(--glass-text-tertiary)'
              }}
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
              </svg>
            </button>
          </div>
          <button
            onClick={handleCreateTicketType}
            className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 rounded-lg font-medium transition-all duration-200"
            style={{ color: '#ffffff' }}
          >
            <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>
            Add Ticket Type
          </button>
        </div>
      </div>

      {ticketTypes.length === 0 ? (
        <div className="text-center py-12 rounded-xl glass-card">
          <svg className="w-12 h-12 mx-auto mb-4" style={{ color: 'var(--glass-text-tertiary)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
          </svg>
          <p className="mb-4" style={{ color: 'var(--glass-text-secondary)' }}>No ticket types created yet</p>
          <button
            onClick={handleCreateTicketType}
            className="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 rounded-lg font-medium transition-all duration-200"
            style={{ color: '#ffffff' }}
          >
            Create Your First Ticket Type
          </button>
        </div>
      ) : (
        <>
          {viewMode === 'card' ? (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {ticketTypes.map(renderTicketCard)}
            </div>
          ) : (
            <div className="rounded-xl overflow-hidden glass-card">
              <table className="w-full">
                <thead style={{ background: 'var(--glass-bg-lg)' }}>
                  <tr>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Name</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Price</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Sold</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Available</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Revenue</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Progress</th>
                    <th className="text-left py-3 px-4 font-medium" style={{ color: 'var(--glass-text-secondary)' }}>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {ticketTypes.map(renderTicketRow)}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {showModal && (
        <TicketTypeModal
          eventId={eventId}
          ticketType={editingTicketType}
          onClose={() => setShowModal(false)}
          onSave={loadData}
        />
      )}
    </div>
  );
}