import { useState, useEffect } from 'react';
import { loadSalesData, exportSalesData, type SalesData, type SalesFilter } from '../../lib/sales-analytics';
import { loadTicketTypes } from '../../lib/ticket-management';
import { refundTicket, checkInTicket } from '../../lib/ticket-management';
import { formatCurrency } from '../../lib/event-management';
import OrdersTable from '../tables/OrdersTable';

interface OrdersTabProps {
  eventId: string;
}

export default function OrdersTab({ eventId }: OrdersTabProps) {
  const [orders, setOrders] = useState<SalesData[]>([]);
  const [filteredOrders, setFilteredOrders] = useState<SalesData[]>([]);
  const [ticketTypes, setTicketTypes] = useState<any[]>([]);
  const [filters, setFilters] = useState<SalesFilter>({});
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedOrder, setSelectedOrder] = useState<SalesData | null>(null);
  const [showOrderDetails, setShowOrderDetails] = useState(false);
  const [loading, setLoading] = useState(true);
  const [exporting, setExporting] = useState(false);

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

  useEffect(() => {
    applyFilters();
  }, [orders, filters, searchTerm]);

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

    } finally {
      setLoading(false);
    }
  };

  const applyFilters = () => {
    let filtered = [...orders];

    // Apply ticket type filter
    if (filters.ticketTypeId) {
      filtered = filtered.filter(order => order.ticket_type_id === filters.ticketTypeId);
    }

    // Apply status filter
    if (filters.status) {
      if (filters.status === 'confirmed') {
        filtered = filtered.filter(order => !order.refund_status || order.refund_status === null);
      } else if (filters.status === 'refunded') {
        filtered = filtered.filter(order => order.refund_status === 'completed');
      } else if (filters.status === 'pending') {
        filtered = filtered.filter(order => order.refund_status === 'pending');
      } else if (filters.status === 'cancelled') {
        filtered = filtered.filter(order => order.refund_status === 'failed');
      }
    }

    // Apply check-in filter
    if (filters.checkedIn !== undefined) {
      filtered = filtered.filter(order => order.checked_in === filters.checkedIn);
    }

    // Apply search filter
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      filtered = filtered.filter(order => 
        order.purchaser_name.toLowerCase().includes(term) ||
        order.purchaser_email.toLowerCase().includes(term) ||
        order.uuid.toLowerCase().includes(term)
      );
    }

    setFilteredOrders(filtered);
  };

  const handleFilterChange = (key: keyof SalesFilter, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }));
  };

  const clearFilters = () => {
    setFilters({});
    setSearchTerm('');
  };

  const handleViewOrder = (order: SalesData) => {
    setSelectedOrder(order);
    setShowOrderDetails(true);
  };

  const handleRefundOrder = async (order: SalesData) => {
    if (confirm(`Are you sure you want to refund ${order.purchaser_name}'s ticket?`)) {
      const success = await refundTicket(order.id);
      if (success) {
        setOrders(prev => prev.map(o => 
          o.id === order.id ? { ...o, refund_status: 'completed' } : o
        ));
      }
    }
  };

  const handleCheckInOrder = async (order: SalesData) => {
    const success = await checkInTicket(order.id);
    if (success) {
      setOrders(prev => prev.map(o => 
        o.id === order.id ? { ...o, checked_in: true } : o
      ));
    }
  };

  const handleExport = async (format: 'csv' | 'json' = 'csv') => {
    setExporting(true);
    try {
      const exportData = await exportSalesData(eventId, format);
      const blob = new Blob([exportData], { 
        type: format === 'csv' ? 'text/csv' : 'application/json' 
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `orders-${new Date().toISOString().split('T')[0]}.${format}`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {

    } finally {
      setExporting(false);
    }
  };

  const getOrderStats = () => {
    const totalOrders = filteredOrders.length;
    const confirmedOrders = filteredOrders.filter(o => !o.refund_status || o.refund_status === null).length;
    const refundedOrders = filteredOrders.filter(o => o.refund_status === 'completed').length;
    const checkedInOrders = filteredOrders.filter(o => o.checked_in).length;
    const totalRevenue = filteredOrders
      .filter(o => !o.refund_status || o.refund_status === null)
      .reduce((sum, o) => sum + o.price, 0);

    return {
      totalOrders,
      confirmedOrders,
      refundedOrders,
      checkedInOrders,
      totalRevenue
    };
  };

  const stats = getOrderStats();

  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">Orders & Sales</h2>
        <div className="flex items-center gap-3">
          <button
            onClick={() => handleExport('csv')}
            disabled={exporting}
            className="flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors disabled:opacity-50"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            {exporting ? 'Exporting...' : 'Export CSV'}
          </button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-5 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 Orders</div>
          <div className="text-2xl font-bold text-white">{stats.totalOrders}</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">Confirmed</div>
          <div className="text-2xl font-bold text-green-400">{stats.confirmedOrders}</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">Refunded</div>
          <div className="text-2xl font-bold text-red-400">{stats.refundedOrders}</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">Checked In</div>
          <div className="text-2xl font-bold text-blue-400">{stats.checkedInOrders}</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">Revenue</div>
          <div className="text-2xl font-bold text-white">{formatCurrency(stats.totalRevenue)}</div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-white/5 border border-white/20 rounded-xl p-6">
        <h3 className="text-lg font-semibold text-white mb-4">Filters</h3>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm text-white/80 mb-2">Search</label>
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Name, email, or ticket ID..."
              className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
          <div>
            <label className="block text-sm text-white/80 mb-2">Ticket Type</label>
            <select
              value={filters.ticketTypeId || ''}
              onChange={(e) => handleFilterChange('ticketTypeId', e.target.value || undefined)}
              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"
            >
              <option value="">All Ticket Types</option>
              {ticketTypes.map(type => (
                <option key={type.id} value={type.id}>{type.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm text-white/80 mb-2">Status</label>
            <select
              value={filters.status || ''}
              onChange={(e) => handleFilterChange('status', e.target.value || undefined)}
              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"
            >
              <option value="">All Statuses</option>
              <option value="confirmed">Confirmed</option>
              <option value="pending">Pending</option>
              <option value="refunded">Refunded</option>
              <option value="cancelled">Cancelled</option>
            </select>
          </div>
          <div>
            <label className="block text-sm text-white/80 mb-2">Check-in Status</label>
            <select
              value={filters.checkedIn === undefined ? '' : filters.checkedIn.toString()}
              onChange={(e) => handleFilterChange('checkedIn', e.target.value === '' ? undefined : e.target.value === 'true')}
              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"
            >
              <option value="">All</option>
              <option value="true">Checked In</option>
              <option value="false">Not Checked In</option>
            </select>
          </div>
        </div>
        <div className="mt-4 flex justify-end">
          <button
            onClick={clearFilters}
            className="px-4 py-2 text-white/80 hover:text-white transition-colors"
          >
            Clear Filters
          </button>
        </div>
      </div>

      {/* Orders Table */}
      <div className="bg-white/5 border border-white/20 rounded-xl p-6">
        <OrdersTable
          orders={filteredOrders}
          onViewOrder={handleViewOrder}
          onRefundOrder={handleRefundOrder}
          onCheckIn={handleCheckInOrder}
          showActions={true}
          showCheckIn={true}
        />
      </div>

      {/* Order Details Modal */}
      {showOrderDetails && selectedOrder && (
        <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-2xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-light text-white">Order Details</h3>
                <button
                  onClick={() => setShowOrderDetails(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-6">
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <h4 className="text-lg font-semibold text-white mb-3">Customer Information</h4>
                    <div className="space-y-2">
                      <div>
                        <span className="text-white/60 text-sm">Name:</span>
                        <div className="text-white font-medium">{selectedOrder.purchaser_name}</div>
                      </div>
                      <div>
                        <span className="text-white/60 text-sm">Email:</span>
                        <div className="text-white">{selectedOrder.purchaser_email}</div>
                      </div>
                    </div>
                  </div>

                  <div>
                    <h4 className="text-lg font-semibold text-white mb-3">Order Information</h4>
                    <div className="space-y-2">
                      <div>
                        <span className="text-white/60 text-sm">Order ID:</span>
                        <div className="text-white font-mono text-sm">{selectedOrder.id}</div>
                      </div>
                      <div>
                        <span className="text-white/60 text-sm">Ticket ID:</span>
                        <div className="text-white font-mono text-sm">{selectedOrder.uuid}</div>
                      </div>
                      <div>
                        <span className="text-white/60 text-sm">Purchase Date:</span>
                        <div className="text-white">{new Date(selectedOrder.created_at).toLocaleString()}</div>
                      </div>
                    </div>
                  </div>
                </div>

                <div>
                  <h4 className="text-lg font-semibold text-white mb-3">Ticket Details</h4>
                  <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <span className="text-white/60 text-sm">Ticket Type:</span>
                        <div className="text-white font-medium">{selectedOrder.ticket_types.name}</div>
                      </div>
                      <div>
                        <span className="text-white/60 text-sm">Price Paid:</span>
                        <div className="text-white font-bold">{formatCurrency(selectedOrder.price)}</div>
                      </div>
                      <div>
                        <span className="text-white/60 text-sm">Status:</span>
                        <div className={`font-medium ${
                          (!selectedOrder.refund_status || selectedOrder.refund_status === null) ? 'text-green-400' :
                          selectedOrder.refund_status === 'completed' ? 'text-red-400' :
                          'text-yellow-400'
                        }`}>
                          {(!selectedOrder.refund_status || selectedOrder.refund_status === null) ? 'Confirmed' :
                           selectedOrder.refund_status === 'completed' ? 'Refunded' :
                           selectedOrder.refund_status === 'pending' ? 'Pending' : 'Failed'}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div>
                  <h4 className="text-lg font-semibold text-white mb-3">Check-in Status</h4>
                  <div className="bg-white/5 border border-white/20 rounded-lg p-4">
                    {selectedOrder.checked_in ? (
                      <div className="flex items-center text-green-400">
                        <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        Checked In
                      </div>
                    ) : (
                      <div className="flex items-center justify-between">
                        <div className="flex items-center text-white/60">
                          <svg className="w-5 h-5 mr-2" 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>
                          Not Checked In
                        </div>
                        {(!selectedOrder.refund_status || selectedOrder.refund_status === null) && (
                          <button
                            onClick={() => {
                              handleCheckInOrder(selectedOrder);
                              setShowOrderDetails(false);
                            }}
                            className="px-4 py-2 rounded-lg transition-all duration-200 hover:shadow-lg hover:scale-105"
                            style={{
                              background: 'var(--success-color)',
                              color: 'white'
                            }}
                          >
                            Check In Now
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                </div>

                <div className="flex justify-end space-x-3">
                  <button
                    onClick={() => setShowOrderDetails(false)}
                    className="px-6 py-3 text-white/80 hover:text-white transition-colors"
                  >
                    Close
                  </button>
                  {selectedOrder.status === 'confirmed' && (
                    <button
                      onClick={() => {
                        handleRefundOrder(selectedOrder);
                        setShowOrderDetails(false);
                      }}
                      className="px-6 py-3 rounded-lg transition-all duration-200 hover:shadow-lg hover:scale-105"
                      style={{
                        background: 'var(--error-color)',
                        color: 'white'
                      }}
                    >
                      Refund Order
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}