import React, { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Ticket as TicketIcon, AlertCircle, CheckCircle2, Clock, Circle, Loader2, XCircle, Plus, RefreshCw } from 'lucide-react';
import { useTickets, useRefreshTicketEmails } from '../../hooks/useTickets';
import { useTicketWebSocket } from '../../hooks/useTicketWebSocket';
import { Ticket, TicketStatus } from '../../types';
import TicketModal from '../../components/TicketModal';
import Portal from '../../components/Portal';
import toast from 'react-hot-toast';

const PlatformSupport: React.FC = () => {
  const { t } = useTranslation();

  // Enable real-time ticket updates via WebSocket
  useTicketWebSocket({ showToasts: true });
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [statusFilter, setStatusFilter] = useState<TicketStatus | 'ALL'>('ALL');

  // Fetch all tickets (platform admins see all) - always fetch all for counts
  const { data: allTickets = [], isLoading, error, refetch } = useTickets();

  // Refresh emails mutation
  const refreshEmails = useRefreshTicketEmails();

  // Compute ticket counts by status
  const ticketCounts = useMemo(() => {
    const counts: Record<string, number> = {
      ALL: allTickets.length,
      OPEN: 0,
      IN_PROGRESS: 0,
      AWAITING_RESPONSE: 0,
      RESOLVED: 0,
      CLOSED: 0,
    };
    allTickets.forEach((ticket) => {
      if (counts[ticket.status] !== undefined) {
        counts[ticket.status]++;
      }
    });
    return counts;
  }, [allTickets]);

  // Filter tickets based on selected status
  const platformTickets = useMemo(() => {
    if (statusFilter === 'ALL') return allTickets;
    return allTickets.filter((ticket) => ticket.status === statusFilter);
  }, [allTickets, statusFilter]);

  const handleRefreshEmails = async () => {
    try {
      const result = await refreshEmails.mutateAsync();
      if (result.processed > 0) {
        toast.success(`Processed ${result.processed} new email(s)`);
        refetch();
      } else {
        toast.success('No new emails found');
      }
    } catch (error: any) {
      toast.error(error.response?.data?.error || 'Failed to refresh emails');
    }
  };

  const getStatusIcon = (status: TicketStatus) => {
    switch (status) {
      case 'OPEN': return <Circle size={14} className="text-green-500" />;
      case 'IN_PROGRESS': return <Loader2 size={14} className="text-blue-500 animate-spin" />;
      case 'AWAITING_RESPONSE': return <Clock size={14} className="text-orange-500" />;
      case 'RESOLVED': return <CheckCircle2 size={14} className="text-gray-500" />;
      case 'CLOSED': return <XCircle size={14} className="text-gray-400" />;
      default: return <AlertCircle size={14} />;
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'URGENT': return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400';
      case 'HIGH': return 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400';
      case 'MEDIUM': return 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400';
      case 'LOW': return 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400';
      default: return 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300';
    }
  };

  const statusTabs: { key: TicketStatus | 'ALL'; label: string }[] = [
    { key: 'ALL', label: t('tickets.tabs.all', 'All') },
    { key: 'OPEN', label: t('tickets.tabs.open', 'Open') },
    { key: 'IN_PROGRESS', label: t('tickets.tabs.inProgress', 'In Progress') },
    { key: 'AWAITING_RESPONSE', label: t('tickets.tabs.awaitingResponse', 'Awaiting') },
    { key: 'RESOLVED', label: t('tickets.tabs.resolved', 'Resolved') },
    { key: 'CLOSED', label: t('tickets.tabs.closed', 'Closed') },
  ];

  const handleTicketClick = (ticket: Ticket) => {
    setSelectedTicket(ticket);
    setIsModalOpen(true);
  };

  const handleNewTicket = () => {
    setSelectedTicket(null);
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedTicket(null);
  };

  if (error) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="mx-auto h-12 w-12 text-red-400" />
        <p className="mt-4 text-red-600 dark:text-red-400">{t('tickets.errorLoading')}</p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900 dark:text-white">{t('platform.supportTickets')}</h2>
          <p className="text-gray-500 dark:text-gray-400">{t('platform.supportDescription')}</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={handleRefreshEmails}
            disabled={refreshEmails.isPending}
            className="inline-flex items-center gap-2 px-4 py-2 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
            title="Check for new emails"
          >
            <RefreshCw size={18} className={refreshEmails.isPending ? 'animate-spin' : ''} />
            {refreshEmails.isPending ? 'Checking...' : 'Check Emails'}
          </button>
          <button
            onClick={handleNewTicket}
            className="inline-flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors"
          >
            <Plus size={18} />
            {t('tickets.newTicket')}
          </button>
        </div>
      </div>

      {/* Status Tabs */}
      <div className="flex flex-wrap gap-2 border-b border-gray-200 dark:border-gray-700 pb-2">
        {statusTabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setStatusFilter(tab.key)}
            className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors flex items-center gap-2 ${
              statusFilter === tab.key
                ? 'bg-brand-600 text-white'
                : 'text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700'
            }`}
          >
            {tab.label}
            {ticketCounts[tab.key] > 0 && (
              <span className={`px-1.5 py-0.5 text-xs rounded-full ${
                statusFilter === tab.key
                  ? 'bg-white/20 text-white'
                  : 'bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
              }`}>
                {ticketCounts[tab.key]}
              </span>
            )}
          </button>
        ))}
      </div>

      {isLoading ? (
        <div className="text-center py-12">
          <Loader2 className="mx-auto h-8 w-8 animate-spin text-brand-600" />
          <p className="mt-4 text-gray-500">{t('common.loading')}</p>
        </div>
      ) : platformTickets.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <TicketIcon className="mx-auto h-12 w-12 text-gray-400" />
          <p className="mt-4 text-gray-500 dark:text-gray-400">{t('tickets.noTicketsFound')}</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4">
          {platformTickets.map((ticket) => (
            <div
              key={ticket.id}
              onClick={() => handleTicketClick(ticket)}
              className="bg-white dark:bg-gray-800 p-4 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm hover:shadow-md transition-shadow cursor-pointer"
              style={{
                borderLeft: ticket.source_email_address
                  ? `4px solid ${ticket.source_email_address.color}`
                  : undefined
              }}
            >
              <div className="flex items-start justify-between">
                <div className="flex items-start gap-4">
                  <div className={`p-2 rounded-lg shrink-0 ${getPriorityColor(ticket.priority)}`}>
                    <TicketIcon size={20} />
                  </div>
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-semibold text-gray-900 dark:text-white">{ticket.subject}</h3>
                      <span className="text-xs px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-600">
                        #{ticket.id}
                      </span>
                      <span className={`text-xs px-2 py-0.5 rounded-full ${
                        ticket.ticketType === 'PLATFORM' ? 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400' :
                        ticket.ticketType === 'CUSTOMER' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' :
                        'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
                      }`}>
                        {t(`tickets.types.${ticket.ticketType.toLowerCase()}`)}
                      </span>
                      {ticket.source_email_address && (
                        <span
                          className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-white text-xs font-medium"
                          style={{ backgroundColor: ticket.source_email_address.color }}
                        >
                          {ticket.source_email_address.display_name}
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
                      {t('platform.reportedBy')} <span className="font-medium text-gray-900 dark:text-white">{ticket.creatorFullName || ticket.creatorEmail}</span>
                      {ticket.category && (
                        <span className="ml-2 text-xs px-2 py-0.5 rounded bg-gray-100 dark:bg-gray-700">
                          {t(`tickets.categories.${ticket.category.toLowerCase()}`)}
                        </span>
                      )}
                    </p>
                    <div className="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
                      <span className="flex items-center gap-1">
                        <Clock size={12} /> {new Date(ticket.createdAt).toLocaleDateString()}
                      </span>
                      <span className="flex items-center gap-1 font-medium">
                        {getStatusIcon(ticket.status)}
                        {t(`tickets.statuses.${ticket.status.toLowerCase()}`)}
                      </span>
                      {ticket.assigneeFullName && (
                        <span className="text-gray-400">
                          {t('tickets.assignedTo')}: {ticket.assigneeFullName}
                        </span>
                      )}
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  <span className={`inline-block px-2 py-1 rounded text-xs font-medium ${getPriorityColor(ticket.priority)}`}>
                    {t(`tickets.priorities.${ticket.priority.toLowerCase()}`)}
                  </span>
                  {ticket.isOverdue && (
                    <span className="block mt-1 text-xs text-red-600 dark:text-red-400 font-medium">
                      Overdue
                    </span>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Ticket Modal */}
      {isModalOpen && (
        <Portal>
          <TicketModal
            ticket={selectedTicket}
            onClose={handleCloseModal}
            defaultTicketType="PLATFORM"
          />
        </Portal>
      )}
    </div>
  );
};

export default PlatformSupport;