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

interface AttendeeData {
  email: string;
  name: string;
  ticketCount: number;
  totalSpent: number;
  checkedInCount: number;
  tickets: SalesData[];
}

interface AttendeesTableProps {
  orders: SalesData[];
  onViewAttendee?: (attendee: AttendeeData) => void;
  onCheckInAttendee?: (attendee: AttendeeData) => void;
  onRefundAttendee?: (attendee: AttendeeData) => void;
  showActions?: boolean;
}

export default function AttendeesTable({ 
  orders, 
  onViewAttendee, 
  onCheckInAttendee, 
  onRefundAttendee,
  showActions = true
}: AttendeesTableProps) {
  const [sortField, setSortField] = useState<keyof AttendeeData>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const attendees = useMemo(() => {
    const attendeeMap = new Map<string, AttendeeData>();

    orders.forEach(order => {
      const existing = attendeeMap.get(order.purchaser_email) || {
        email: order.purchaser_email,
        name: order.purchaser_name,
        ticketCount: 0,
        totalSpent: 0,
        checkedInCount: 0,
        tickets: []
      };

      existing.tickets.push(order);
      if (!order.refund_status || order.refund_status === null) {
        existing.ticketCount += 1;
        existing.totalSpent += order.price;
        if (order.checked_in) {
          existing.checkedInCount += 1;
        }
      }

      attendeeMap.set(order.purchaser_email, existing);
    });

    // Only show attendees with active tickets (ticketCount > 0)
    return Array.from(attendeeMap.values()).filter(attendee => attendee.ticketCount > 0);
  }, [orders]);

  const sortedAttendees = useMemo(() => {
    return [...attendees].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;
    });
  }, [attendees, sortField, sortDirection]);

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

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

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

  const SortIcon = ({ field }: { field: keyof AttendeeData }) => {
    if (sortField !== field) {
      return (
        <svg className="w-4 h-4 text-white/40" 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-white" 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-white" 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 getCheckInStatus = (attendee: AttendeeData) => {
    if (attendee.checkedInCount === 0) {
      return (
        <span className="text-white/60 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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Not Checked In
        </span>
      );
    } else if (attendee.checkedInCount === attendee.ticketCount) {
      return (
        <span className="text-green-400 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>
      );
    } else {
      return (
        <span className="text-yellow-400 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="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Partial ({attendee.checkedInCount}/{attendee.ticketCount})
        </span>
      );
    }
  };

  const exportToCSV = () => {
    const headers = ['Name', 'Email', 'Tickets', 'Total Spent', 'Checked In', 'Check-in Status'];
    const csvContent = [
      headers.join(','),
      ...attendees.map(attendee => [
        `"${attendee.name}"`,
        `"${attendee.email}"`,
        attendee.ticketCount,
        formatCurrency(attendee.totalSpent),
        attendee.checkedInCount,
        attendee.checkedInCount === attendee.ticketCount ? 'Complete' : 
        attendee.checkedInCount > 0 ? 'Partial' : 'Not Checked In'
      ].join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `attendees-${new Date().toISOString().split('T')[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  };

  if (attendees.length === 0) {
    return (
      <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="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>
        <p className="text-white/60">No attendees found</p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <div className="text-white/80">
          {attendees.length} attendees • {attendees.reduce((sum, a) => sum + a.ticketCount, 0)} tickets
        </div>
        <button
          onClick={exportToCSV}
          className="flex items-center space-x-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors"
        >
          <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>
          <span>Export CSV</span>
        </button>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full">
          <thead>
            <tr className="border-b border-white/20">
              <th className="text-left py-3 px-4 text-white/80 font-medium">
                <button
                  onClick={() => handleSort('name')}
                  className="flex items-center space-x-1 hover:text-white transition-colors"
                >
                  <span>Name</span>
                  <SortIcon field="name" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-white/80 font-medium">
                <button
                  onClick={() => handleSort('email')}
                  className="flex items-center space-x-1 hover:text-white transition-colors"
                >
                  <span>Email</span>
                  <SortIcon field="email" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-white/80 font-medium">
                <button
                  onClick={() => handleSort('ticketCount')}
                  className="flex items-center space-x-1 hover:text-white transition-colors"
                >
                  <span>Tickets</span>
                  <SortIcon field="ticketCount" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-white/80 font-medium">
                <button
                  onClick={() => handleSort('totalSpent')}
                  className="flex items-center space-x-1 hover:text-white transition-colors"
                >
                  <span>Total Spent</span>
                  <SortIcon field="totalSpent" />
                </button>
              </th>
              <th className="text-left py-3 px-4 text-white/80 font-medium">
                <button
                  onClick={() => handleSort('checkedInCount')}
                  className="flex items-center space-x-1 hover:text-white transition-colors"
                >
                  <span>Check-in Status</span>
                  <SortIcon field="checkedInCount" />
                </button>
              </th>
              {showActions && (
                <th className="text-right py-3 px-4 text-white/80 font-medium">Actions</th>
              )}
            </tr>
          </thead>
          <tbody>
            {paginatedAttendees.map((attendee) => (
              <tr key={attendee.email} className="border-b border-white/10 hover:bg-white/5 transition-colors">
                <td className="py-3 px-4">
                  <div className="text-white font-medium">{attendee.name}</div>
                </td>
                <td className="py-3 px-4">
                  <div className="text-white/80">{attendee.email}</div>
                </td>
                <td className="py-3 px-4">
                  <div className="text-white">{attendee.ticketCount}</div>
                </td>
                <td className="py-3 px-4">
                  <div className="text-white font-medium">{formatCurrency(attendee.totalSpent)}</div>
                </td>
                <td className="py-3 px-4">
                  {getCheckInStatus(attendee)}
                </td>
                {showActions && (
                  <td className="py-3 px-4 text-right">
                    <div className="flex items-center justify-end space-x-2">
                      {onViewAttendee && (
                        <button
                          onClick={() => onViewAttendee(attendee)}
                          className="p-2 text-white/60 hover:text-white 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>
                      )}
                      {onCheckInAttendee && attendee.checkedInCount < attendee.ticketCount && (
                        <button
                          onClick={() => onCheckInAttendee(attendee)}
                          className="p-2 text-white/60 hover:text-green-400 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>
                      )}
                      {onRefundAttendee && attendee.ticketCount > 0 && (
                        <button
                          onClick={() => onRefundAttendee(attendee)}
                          className="p-2 text-white/60 hover:text-red-400 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-white/60 text-sm">
            Showing {((currentPage - 1) * itemsPerPage) + 1} to {Math.min(currentPage * itemsPerPage, attendees.length)} of {attendees.length} attendees
          </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-white/10 text-white rounded-lg hover:bg-white/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Previous
            </button>
            <span className="text-white/80 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-white/10 text-white rounded-lg hover:bg-white/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
}