import { useState, useMemo } from 'react';
import type { SalesData } from '../../lib/sales-analytics';
import { formatCurrency } from '../../lib/event-management';

interface OrdersTableProps {
  orders: SalesData[];
  onViewOrder?: (order: SalesData) => void;
  onRefundOrder?: (order: SalesData) => void;
  onCheckIn?: (order: SalesData) => void;
  showActions?: boolean;
  showCheckIn?: boolean;
}

export default function OrdersTable({ 
  orders, 
  onViewOrder, 
  onRefundOrder, 
  onCheckIn,
  showActions = true,
  showCheckIn = true
}: OrdersTableProps) {
  const [sortField, setSortField] = useState<keyof SalesData>('created_at');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const sortedOrders = useMemo(() => {
    return [...orders].sort((a, b) => {
      const aValue = a[sortField];
      const bValue = b[sortField];
      
      if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
      if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
      return 0;
    });
  }, [orders, sortField, sortDirection]);

  const paginatedOrders = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return sortedOrders.slice(startIndex, startIndex + itemsPerPage);
  }, [sortedOrders, currentPage]);

  const totalPages = Math.ceil(orders.length / itemsPerPage);

  const handleSort = (field: keyof SalesData) => {
    if (sortField === field) {
      setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  };

  const SortIcon = ({ field }: { field: keyof SalesData }) => {
    if (sortField !== field) {
      return (
        <svg className="w-4 h-4 text-[var(--ui-text-muted)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l4-4 4 4m0 6l-4 4-4-4" />
        </svg>
      );
    }
    
    return sortDirection === 'asc' ? (
      <svg className="w-4 h-4 text-[var(--ui-text-primary)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
      </svg>
    ) : (
      <svg className="w-4 h-4 text-[var(--ui-text-primary)]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
      </svg>
    );
  };

  const getStatusBadge = (refund_status: string | null) => {
    const status = (!refund_status || refund_status === null) ? 'confirmed' : 
                   refund_status === 'completed' ? 'refunded' : 
                   refund_status === 'pending' ? 'pending' : 'cancelled';
    const statusClasses = {
      confirmed: 'bg-[var(--success-bg)] text-[var(--success-color)] border-[var(--success-border)]',
      pending: 'bg-[var(--warning-bg)] text-[var(--warning-color)] border-[var(--warning-border)]',
      refunded: 'bg-[var(--error-bg)] text-[var(--error-color)] border-[var(--error-border)]',
      cancelled: 'bg-[var(--ui-bg-secondary)] text-[var(--ui-text-tertiary)] border-[var(--ui-border-secondary)]'
    };

    return (
      <span className={`px-2 py-1 text-xs rounded-lg border ${statusClasses[status as keyof typeof statusClasses] || statusClasses.pending}`}>
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </span>
    );
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: 'numeric',
      minute: '2-digit'
    });
  };

  if (orders.length === 0) {
    return (
      <div className="text-center py-12">
        <svg className="w-12 h-12 text-[var(--ui-text-muted)] mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
        </svg>
        <p className="text-[var(--ui-text-tertiary)]">No orders found</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-[var(--ui-border-primary)]">
              <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                <button
                  onClick={() => handleSort('purchaser_name')}
                  className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                >
                  <span>Customer</span>
                  <SortIcon field="purchaser_name" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                <button
                  onClick={() => handleSort('ticket_types')}
                  className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                >
                  <span>Ticket Type</span>
                  <SortIcon field="ticket_types" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                <button
                  onClick={() => handleSort('price')}
                  className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                >
                  <span>Amount</span>
                  <SortIcon field="price" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                <button
                  onClick={() => handleSort('refund_status')}
                  className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                >
                  <span>Status</span>
                  <SortIcon field="refund_status" />
                </button>
              </th>
              {showCheckIn && (
                <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                  <button
                    onClick={() => handleSort('checked_in')}
                    className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                  >
                    <span>Check-in</span>
                    <SortIcon field="checked_in" />
                  </button>
                </th>
              )}
              <th className="text-left py-3 px-4 text-[var(--ui-text-secondary)] font-medium">
                <button
                  onClick={() => handleSort('created_at')}
                  className="flex items-center space-x-1 hover:text-[var(--ui-text-primary)] transition-colors"
                >
                  <span>Date</span>
                  <SortIcon field="created_at" />
                </button>
              </th>
              {showActions && (
                <th className="text-right py-3 px-4 text-[var(--ui-text-secondary)] font-medium">Actions</th>
              )}
            </tr>
          </thead>
          <tbody>
            {paginatedOrders.map((order) => (
              <tr key={order.id} className="border-b border-[var(--ui-border-secondary)] hover:bg-[var(--ui-bg-secondary)] transition-colors">
                <td className="py-3 px-4">
                  <div>
                    <div className="text-[var(--ui-text-primary)] font-medium">{order.purchaser_name}</div>
                    <div className="text-[var(--ui-text-tertiary)] text-sm">{order.purchaser_email}</div>
                  </div>
                </td>
                <td className="py-3 px-4">
                  <div className="text-[var(--ui-text-primary)]">{order.ticket_types.name}</div>
                </td>
                <td className="py-3 px-4">
                  <div className="text-[var(--ui-text-primary)] font-medium">{formatCurrency(order.price)}</div>
                </td>
                <td className="py-3 px-4">
                  {getStatusBadge(order.refund_status)}
                </td>
                {showCheckIn && (
                  <td className="py-3 px-4">
                    {order.checked_in ? (
                      <span className="text-[var(--success-color)] flex items-center">
                        <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                        Checked In
                      </span>
                    ) : (
                      <span className="text-[var(--ui-text-tertiary)]">Not Checked In</span>
                    )}
                  </td>
                )}
                <td className="py-3 px-4">
                  <div className="text-[var(--ui-text-secondary)] text-sm">{formatDate(order.created_at)}</div>
                </td>
                {showActions && (
                  <td className="py-3 px-4 text-right">
                    <div className="flex items-center justify-end space-x-2">
                      {onViewOrder && (
                        <button
                          onClick={() => onViewOrder(order)}
                          className="p-2 text-[var(--ui-text-tertiary)] hover:text-[var(--ui-text-primary)] transition-colors"
                          title="View Details"
                        >
                          <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>
                      )}
                      {onCheckIn && !order.checked_in && (!order.refund_status || order.refund_status === null) && (
                        <button
                          onClick={() => onCheckIn(order)}
                          className="p-2 text-[var(--ui-text-tertiary)] hover:text-[var(--success-color)] transition-colors"
                          title="Check In"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                          </svg>
                        </button>
                      )}
                      {onRefundOrder && (!order.refund_status || order.refund_status === null) && (
                        <button
                          onClick={() => onRefundOrder(order)}
                          className="p-2 text-[var(--ui-text-tertiary)] hover:text-[var(--error-color)] transition-colors"
                          title="Refund"
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 15v-1a4 4 0 00-4-4H8m0 0l3 3m-3-3l3-3m9 14V5a2 2 0 00-2-2H6a2 2 0 00-2 2v16l4-2 4 2 4-2 4 2z" />
                          </svg>
                        </button>
                      )}
                    </div>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-[var(--ui-text-tertiary)] text-sm">
            Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, orders.length)} of {orders.length} orders
          </div>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className="px-3 py-1 bg-[var(--ui-bg-primary)] text-[var(--ui-text-primary)] rounded-lg hover:bg-[var(--ui-bg-elevated)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="text-[var(--ui-text-secondary)] text-sm">
              Page {currentPage} of {totalPages}
            </span>
            <button
              onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
              disabled={currentPage === totalPages}
              className="px-3 py-1 bg-[var(--ui-bg-primary)] text-[var(--ui-text-primary)] rounded-lg hover:bg-[var(--ui-bg-elevated)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}