// app/components/admin/support/SupportTicketsTable.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import toast from 'react-hot-toast';
import { usePermissions } from '@/hooks/usePermissions';
import { PERMISSIONS } from '@/lib/permissions';
import { useAlert } from '@/contexts/AlertContext';
import DataTable from '@/app/components/admin/CommonComponents/DataTable';
import TablePagination from '@/app/components/admin/CommonComponents/TablePagination';
import TableFilters from '@/app/components/admin/CommonComponents/TableFilters';
import { BaseTableItem, FilterConfig, FilterValues, PaginationData, TableColumn, TableAction } from '@/types/admin-table';
import SupportTicketDetailModal from './SupportTicketDetailModal';

interface SupportTicket extends BaseTableItem {
  id: string;
  ticket_number: string;
  user_id: string;
  user_name: string;
  user_email: string;
  subject: string;
  category: string;
  priority: string;
  status: string;
  message: string;
  reply_count: number;
  created_at: string;
  updated_at: string;
}

interface SupportTicketsTableProps {
  initialData?: {
    tickets: SupportTicket[];
    pagination: PaginationData;
  };
}

const categoryColors: Record<string, string> = {
  order: 'bg-var-primary-muted text-var-primary-text',
  payment: 'bg-var-success-bg text-var-success-text',
  technical: 'bg-var-info-bg text-var-info-text',
  website: 'bg-var-warning-bg text-var-warning-text',
  other: 'bg-var-surface-hover text-var-text-muted',
};

const statusColors: Record<string, string> = {
  open: 'bg-var-warning-bg text-var-warning-text',
  in_progress: 'bg-var-primary-muted text-var-primary-text',
  resolved: 'bg-var-success-bg text-var-success-text',
  closed: 'bg-var-surface-hover text-var-text-muted',
};

export default function SupportTicketsTable({ initialData }: SupportTicketsTableProps) {
  const [tickets, setTickets] = useState<SupportTicket[]>(initialData?.tickets || []);
  const [loading, setLoading] = useState(false);
  const [filtersVisible, setFiltersVisible] = useState(false);
  const [pagination, setPagination] = useState<PaginationData>(initialData?.pagination || {
    page: 1,
    limit: 10,
    total: 0,
    pages: 0
  });
  const [filters, setFilters] = useState<FilterValues>({
    search: '',
    status: '',
    priority: '',
    category: ''
  });
  const [selectedTicket, setSelectedTicket] = useState<SupportTicket | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { hasPermission } = usePermissions();
  const { showAlert } = useAlert();

  // Check permissions
  const canViewTicket = hasPermission(PERMISSIONS.SUPPORT_VIEW);
  const canReplyTicket = hasPermission(PERMISSIONS.SUPPORT_REPLY);
  const canUpdateStatus = hasPermission(PERMISSIONS.SUPPORT_UPDATE);
  const canDeleteTicket = hasPermission(PERMISSIONS.SUPPORT_DELETE);

  // Filter configuration
  const filterConfigs: FilterConfig[] = [
    {
      key: 'search',
      label: 'Search',
      type: 'search',
      placeholder: 'Search by ticket #, subject, or user email...'
    },
    {
      key: 'status',
      label: 'Status',
      type: 'select',
      options: [
        { value: 'open', label: 'Open' },
        { value: 'in_progress', label: 'In Progress' },
        { value: 'resolved', label: 'Resolved' },
        { value: 'closed', label: 'Closed' }
      ]
    },
    {
      key: 'priority',
      label: 'Priority',
      type: 'select',
      options: [
        { value: 'low', label: 'Low' },
        { value: 'medium', label: 'Medium' },
        { value: 'high', label: 'High' },
        { value: 'urgent', label: 'Urgent' }
      ]
    },
    {
      key: 'category',
      label: 'Category',
      type: 'select',
      options: [
        { value: 'order', label: 'Order' },
        { value: 'payment', label: 'Payment' },
        { value: 'technical', label: 'Technical' },
        { value: 'website', label: 'Website' },
        { value: 'other', label: 'Other' }
      ]
    }
  ];

  // Fetch tickets with filters and pagination
  const fetchTickets = useCallback(async (page = 1, newFilters = filters) => {
    if (!canViewTicket) return;
    
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pagination.limit.toString(),
        ...newFilters
      });

      const response = await fetch(`/api/backend/admin/support/tickets?${params}`);
      const data = await response.json();

      if (response.ok) {
        setTickets(data.tickets);
        setPagination(data.pagination);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to view support tickets');
        } else {
          toast.error(data.error || 'Failed to fetch tickets');
        }
      }
    } catch (error) {
      toast.error('Failed to fetch tickets');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, [canViewTicket, filters, pagination.limit]);

  // Handle filter changes
  const handleFilterChange = (newFilters: FilterValues) => {
    setFilters(newFilters);
    fetchTickets(1, newFilters);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    fetchTickets(page);
  };

  // Handle view ticket
  const handleViewTicket = (ticket: SupportTicket) => {
    if (!canViewTicket) {
      toast.error('You do not have permission to view ticket details');
      return;
    }
    setSelectedTicket(ticket);
    setIsModalOpen(true);
  };

  // Handle ticket deletion
  const handleDeleteClick = (ticket: SupportTicket) => {
    if (!canDeleteTicket) {
      toast.error('You do not have permission to delete tickets');
      return;
    }

    showAlert({
      title: 'Delete Ticket',
      message: `Are you sure you want to delete ticket "${ticket.ticket_number}"? This action cannot be undone and will remove all replies.`,
      confirmText: 'Delete Ticket',
      cancelText: 'Cancel',
      onConfirm: () => deleteTicket(ticket.id),
    });
  };

  const deleteTicket = async (ticketId: string) => {
    try {
      const response = await fetch(`/api/backend/admin/support/tickets/${ticketId}`, {
        method: 'DELETE',
      });

      const data = await response.json();

      if (response.ok) {
        toast.success('Ticket deleted successfully');
        fetchTickets(pagination.page);
      } else {
        if (response.status === 403) {
          toast.error('You do not have permission to delete tickets');
        } else {
          toast.error(data.error || 'Failed to delete ticket');
        }
      }
    } catch (error) {
      toast.error('Failed to delete ticket');
      console.error(error);
    }
  };

  // Get priority icon
  const getPriorityIcon = (priority: string) => {
    switch(priority) {
      case 'urgent':
        return (
          <svg className="w-4 h-4 text-var-danger" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
        );
      case 'high':
        return (
          <svg className="w-4 h-4 text-var-warning" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
          </svg>
        );
      case 'medium':
        return (
          <svg className="w-4 h-4 text-var-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>
        );
      default:
        return (
          <svg className="w-4 h-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 13l-7 7-7-7" />
          </svg>
        );
    }
  };

  // Table columns configuration
  const columns: TableColumn<SupportTicket>[] = [
    {
      key: 'ticket',
      label: 'Ticket',
      render: (ticket) => (
        <div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-mono font-medium text-var-text">
              {ticket.ticket_number}
            </span>
            {getPriorityIcon(ticket.priority)}
          </div>
          <div className="text-sm font-medium text-var-text mt-1">
            {ticket.subject}
          </div>
        </div>
      )
    },
    {
      key: 'customer',
      label: 'Customer',
      render: (ticket) => (
        <div>
          <div className="text-sm font-medium text-var-text">
            {ticket.user_name || 'Guest'}
          </div>
          <div className="text-xs text-var-text-muted">
            {ticket.user_email}
          </div>
        </div>
      )
    },
    {
      key: 'category',
      label: 'Category',
      render: (ticket) => (
        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${categoryColors[ticket.category]}`}>
          {ticket.category}
        </span>
      )
    },
    {
      key: 'status',
      label: 'Status',
      render: (ticket) => (
        <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${statusColors[ticket.status]}`}>
          {ticket.status.replace('_', ' ')}
        </span>
      )
    },
    {
      key: 'replies',
      label: 'Replies',
      render: (ticket) => (
        <div className="flex items-center gap-1">
          <svg className="w-4 h-4 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
          </svg>
          <span className="text-sm font-medium text-var-text">
            {ticket.reply_count || 0}
          </span>
        </div>
      )
    },
    {
      key: 'created_at',
      label: 'Created',
      render: (ticket) => (
        <div>
          <div className="text-sm text-var-text">
            {new Date(ticket.created_at).toLocaleDateString()}
          </div>
          <div className="text-xs text-var-text-muted">
            {new Date(ticket.created_at).toLocaleTimeString()}
          </div>
        </div>
      )
    }
  ];

  // Table actions configuration
  const actions: TableAction<SupportTicket>[] = [
    // View Button
    ...(canViewTicket ? [{
      key: 'view',
      icon: (
        <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>
      ),
      onClick: (ticket: SupportTicket) => handleViewTicket(ticket),
      condition: () => canViewTicket,
      className: 'text-var-primary hover:text-var-primary-hover hover:bg-var-primary-muted',
      title: 'View ticket details'
    }] : []),
    
    // Delete Button
    ...(canDeleteTicket ? [{
      key: 'delete',
      icon: (
        <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>
      ),
      onClick: (ticket: SupportTicket) => handleDeleteClick(ticket),
      condition: () => canDeleteTicket,
      className: 'text-var-danger hover:text-var-danger-text hover:bg-var-danger-bg',
      title: 'Delete ticket'
    }] : [])
  ];

  useEffect(() => {
    if (!initialData) {
      fetchTickets();
    }
  }, [fetchTickets, initialData]);

  const toggleFilters = () => {
    setFiltersVisible(!filtersVisible);
  };

  return (
    <>
      <div className="bg-var-surface rounded-2xl shadow-var-card border border-var-border overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-var-border bg-var-surface-hover/50">
          <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
            <div>
              <h2 className="text-lg font-semibold text-var-text">Support Tickets</h2>
              <p className="text-sm text-var-text-secondary mt-1">
                {pagination.total} ticket{pagination.total !== 1 ? 's' : ''} found
              </p>
            </div>
            
            {/* Filter Toggle Button */}
            <button
              onClick={toggleFilters}
              className="inline-flex items-center px-3 py-2 bg-var-surface border border-var-border text-var-text-secondary font-medium rounded-xl hover:bg-var-surface-hover hover:text-var-text transition-all duration-200 shadow-var-button"
              title={filtersVisible ? "Hide filters" : "Show filters"}
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              {filtersVisible ? 'Hide Filters' : 'Show Filters'}
            </button>
          </div>

          {/* Filters - Conditionally rendered */}
          {filtersVisible && (
            <div className="mt-4">
              <TableFilters
                filters={filterConfigs}
                onFilterChange={handleFilterChange}
                initialValues={filters}
                className="mt-0"
              />
            </div>
          )}
        </div>

        {/* Table */}
        <DataTable
          data={tickets}
          columns={columns}
          actions={actions}
          loading={loading}
          emptyMessage="No support tickets found"
          emptyDescription="Try adjusting your search or filters"
          keyExtractor={(ticket) => ticket.id}
        />

        {/* Pagination */}
        <TablePagination
          pagination={pagination}
          onPageChange={handlePageChange}
        />
      </div>

      {/* Ticket Detail Modal */}
      {selectedTicket && (
        <SupportTicketDetailModal
          isOpen={isModalOpen}
          onClose={() => {
            setIsModalOpen(false);
            setSelectedTicket(null);
          }}
          ticket={selectedTicket}
          onUpdate={() => fetchTickets(pagination.page)}
          canReply={canReplyTicket}
          canUpdateStatus={canUpdateStatus}
        />
      )}
    </>
  );
}