'use client';

import { useCallback, useEffect, useState } from 'react';
import { 
  MessageCircle, 
  Plus, 
  Search, 
  ChevronRight,
  AlertCircle,
  Clock,
  CheckCircle,
  XCircle,
  X,
  Send
} from 'lucide-react';
import toast from 'react-hot-toast';

// Types
interface Reply {
  id: string;
  ticket_id: string;
  user_id: string;
  is_admin: boolean;
  message: string;
  created_at: string;
}

interface Ticket {
  id: string;
  ticket_number: string;
  subject: string;
  category: string;
  priority: string;
  status: string;
  message: string;
  created_at: string;
  updated_at: string;
  reply_count?: number;
}

interface SupportClientProps {
  initialTickets: Ticket[];
}

const categoryColors: Record<string, string> = {
  order: 'bg-blue-100 text-blue-700',
  payment: 'bg-green-100 text-green-700',
  technical: 'bg-purple-100 text-purple-700',
  website: 'bg-orange-100 text-orange-700',
  other: 'bg-gray-100 text-gray-700',
};

const priorityColors: Record<string, string> = {
  low: 'bg-gray-100 text-gray-700',
  medium: 'bg-blue-100 text-blue-700',
  high: 'bg-orange-100 text-orange-700',
  urgent: 'bg-red-100 text-red-700',
};

const statusColors: Record<string, string> = {
  open: 'bg-yellow-100 text-yellow-700',
  in_progress: 'bg-blue-100 text-blue-700',
  resolved: 'bg-green-100 text-green-700',
  closed: 'bg-gray-100 text-gray-700',
};

const statusIcons: Record<string, React.ReactNode> = {
  open: <AlertCircle className="h-4 w-4" />,
  in_progress: <Clock className="h-4 w-4" />,
  resolved: <CheckCircle className="h-4 w-4" />,
  closed: <XCircle className="h-4 w-4" />,
};

// New Ticket Modal Component
function NewTicketModal({ isOpen, onClose, onSuccess }: { 
  isOpen: boolean; 
  onClose: () => void; 
  onSuccess: (newTicket: Ticket) => void;
}) {
  const [subject, setSubject] = useState('');
  const [category, setCategory] = useState('order');
  const [priority, setPriority] = useState('medium');
  const [message, setMessage] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!subject.trim() || !message.trim()) {
      toast.error('Please fill in all required fields');
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      const response = await fetch('/api/frontend/dashboard/support/tickets', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ subject, category, priority, message }),
      });
      
      const data = await response.json();
      
      if (response.ok) {
        toast.success('Ticket created successfully');
        onSuccess(data.ticket);
        onClose();
        setSubject('');
        setCategory('order');
        setPriority('medium');
        setMessage('');
      } else {
        toast.error(data.message || 'Failed to create ticket');
      }
    } catch (error) {
      console.error('Error creating ticket:', error);
      toast.error('Failed to create ticket');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-2xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex justify-between items-center">
          <div>
            <h3 className="text-lg font-semibold text-gray-900">Create New Ticket</h3>
            <p className="text-sm text-gray-500">Describe your issue and we`ll help you</p>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X className="h-5 w-5" />
          </button>
        </div>
        
        <form onSubmit={handleSubmit} className="p-6 space-y-5">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Subject <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Brief description of your issue"
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent"
              required
            />
          </div>
          
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Category
              </label>
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent"
              >
                <option value="order">Order Related</option>
                <option value="payment">Payment Issue</option>
                <option value="technical">Technical Problem</option>
                <option value="website">Website Related</option>
                <option value="other">Other</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Priority
              </label>
              <select
                value={priority}
                onChange={(e) => setPriority(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent"
              >
                <option value="low">Low</option>
                <option value="medium">Medium</option>
                <option value="high">High</option>
                <option value="urgent">Urgent</option>
              </select>
            </div>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Message <span className="text-red-500">*</span>
            </label>
            <textarea
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              placeholder="Please provide detailed information about your issue..."
              rows={6}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent resize-none"
              required
            />
          </div>
          
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 bg-[#0066FF] text-white rounded-lg hover:bg-[#0052cc] transition-colors disabled:opacity-50"
            >
              {isSubmitting ? 'Creating...' : 'Create Ticket'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// Ticket Card Component
function TicketCard({ ticket, onView }: { ticket: Ticket; onView: (ticket: Ticket) => void }) {
  return (
    <div 
      onClick={() => onView(ticket)}
      className="bg-white border border-gray-200 rounded-xl p-5 hover:shadow-md transition-all cursor-pointer"
    >
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-3">
          <div className={`p-2 rounded-lg ${statusColors[ticket.status]}`}>
            {statusIcons[ticket.status]}
          </div>
          <div>
            <h3 className="font-semibold text-gray-900">{ticket.subject}</h3>
            <p className="text-xs text-gray-500 mt-0.5">{ticket.ticket_number}</p>
          </div>
        </div>
        <ChevronRight className="h-5 w-5 text-gray-400" />
      </div>
      
      <div className="flex items-center gap-3 text-xs">
        <span className={`px-2 py-1 rounded-full ${categoryColors[ticket.category]}`}>
          {ticket.category}
        </span>
        <span className={`px-2 py-1 rounded-full ${priorityColors[ticket.priority]}`}>
          {ticket.priority}
        </span>
        <span className={`px-2 py-1 rounded-full ${statusColors[ticket.status]}`}>
          {ticket.status.replace('_', ' ')}
        </span>
      </div>
      
      <p className="text-sm text-gray-600 mt-3 line-clamp-2">{ticket.message}</p>
      
      <div className="flex items-center justify-between mt-4 pt-3 border-t border-gray-100">
        <span className="text-xs text-gray-500">
          {new Date(ticket.created_at).toLocaleDateString()}
        </span>
        {ticket.reply_count && ticket.reply_count > 0 && (
          <span className="text-xs text-[#0066FF]">
            {ticket.reply_count} {ticket.reply_count === 1 ? 'reply' : 'replies'}
          </span>
        )}
      </div>
    </div>
  );
}

// Ticket Detail Modal Component
function TicketDetailModal({ ticket, onClose, onUpdate }: { 
  ticket: Ticket; 
  onClose: () => void; 
  onUpdate: (updatedTicket: Ticket) => void;
}) {
  const [replies, setReplies] = useState<Reply[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [isSending, setIsSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const [currentTicket, setCurrentTicket] = useState<Ticket>(ticket);

  const fetchReplies = useCallback(async () => {
    try {
      const response = await fetch(`/api/frontend/dashboard/support/tickets/${currentTicket.id}/replies`);
      const data = await response.json();
      if (response.ok) {
        setReplies(data.replies || []);
      }
    } catch (error) {
      console.error('Error fetching replies:', error);
    } finally {
      setLoading(false);
    }
  }, [currentTicket.id]);

  const fetchTicketStatus = useCallback(async () => {
    try {
      const response = await fetch(`/api/frontend/dashboard/support/tickets/${currentTicket.id}`);
      const data = await response.json();
      if (response.ok && data.ticket) {
        setCurrentTicket(data.ticket);
        onUpdate(data.ticket);
      }
    } catch (error) {
      console.error('Error fetching ticket status:', error);
    }
  }, [currentTicket.id, onUpdate]);

  const handleSendReply = async () => {
    if (!newMessage.trim()) {
      toast.error('Please enter a message');
      return;
    }
    
    setIsSending(true);
    try {
      const response = await fetch(`/api/frontend/dashboard/support/tickets/${currentTicket.id}/replies`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: newMessage }),
      });
      
      if (response.ok) {
        toast.success('Reply sent successfully');
        setNewMessage('');
        await fetchReplies();
        await fetchTicketStatus();
      } else {
        toast.error('Failed to send reply');
      }
    } catch (error) {
      console.error('Error sending reply:', error);
      toast.error('Failed to send reply');
    } finally {
      setIsSending(false);
    }
  };

  useEffect(() => {
    fetchReplies();
  }, [fetchReplies]);

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white rounded-2xl max-w-3xl w-full mx-4 max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex justify-between items-center">
          <div className="flex-1">
            <div className="flex items-center gap-3">
              <h3 className="text-lg font-semibold text-gray-900">{currentTicket.subject}</h3>
              <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[currentTicket.status]}`}>
                {currentTicket.status.replace('_', ' ')}
              </span>
            </div>
            <p className="text-sm text-gray-500 mt-1">Ticket #{currentTicket.ticket_number}</p>
          </div>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600">
            <X className="h-5 w-5" />
          </button>
        </div>
        
        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-6 space-y-4">
          {/* Original Ticket Message */}
          <div className="bg-gray-50 rounded-xl p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center">
                  <span className="text-blue-600 text-sm font-bold">U</span>
                </div>
                <span className="font-medium text-gray-900">You</span>
              </div>
              <span className="text-xs text-gray-500">
                {new Date(currentTicket.created_at).toLocaleString()}
              </span>
            </div>
            <p className="text-gray-700 whitespace-pre-wrap">{currentTicket.message}</p>
          </div>
          
          {/* Replies */}
          {loading ? (
            <div className="text-center py-8">
              <div className="w-8 h-8 border-4 border-gray-200 border-t-[#0066FF] rounded-full animate-spin mx-auto" />
            </div>
          ) : (
            replies.map((reply) => (
              <div key={reply.id} className={`${reply.is_admin ? 'ml-8' : ''}`}>
                <div className={`rounded-xl p-4 ${reply.is_admin ? 'bg-blue-50' : 'bg-gray-50'}`}>
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                        reply.is_admin ? 'bg-[#0066FF]' : 'bg-gray-300'
                      }`}>
                        <span className={`text-sm font-bold ${reply.is_admin ? 'text-white' : 'text-gray-600'}`}>
                          {reply.is_admin ? 'A' : 'U'}
                        </span>
                      </div>
                      <span className="font-medium text-gray-900">
                        {reply.is_admin ? 'Support Team' : 'You'}
                      </span>
                      {reply.is_admin && (
                        <span className="text-xs text-[#0066FF] font-medium">Admin</span>
                      )}
                    </div>
                    <span className="text-xs text-gray-500">
                      {new Date(reply.created_at).toLocaleString()}
                    </span>
                  </div>
                  <p className="text-gray-700 whitespace-pre-wrap">{reply.message}</p>
                </div>
              </div>
            ))
          )}
        </div>
        
        {/* Reply Input */}
        <div className="border-t border-gray-200 p-4">
          <textarea
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
            placeholder="Type your reply here..."
            rows={3}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent resize-none"
          />
          <div className="flex justify-end mt-3">
            <button
              onClick={handleSendReply}
              disabled={isSending || !newMessage.trim()}
              className="inline-flex items-center px-4 py-2 bg-[#0066FF] text-white rounded-lg hover:bg-[#0052cc] transition-colors disabled:opacity-50"
            >
              {isSending ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                  Sending...
                </>
              ) : (
                <>
                  <Send className="h-4 w-4 mr-2" />
                  Send Reply
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// Main Support Client Component
export default function SupportClient({ initialTickets }: SupportClientProps) {
  const [tickets, setTickets] = useState<Ticket[]>(initialTickets);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);

  const filteredTickets = tickets.filter(ticket => {
    const matchesSearch = ticket.subject.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         ticket.message.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || ticket.category === selectedCategory;
    const matchesStatus = selectedStatus === 'all' || ticket.status === selectedStatus;
    return matchesSearch && matchesCategory && matchesStatus;
  });

  const handleTicketCreated = (newTicket: Ticket) => {
    setTickets(prevTickets => [newTicket, ...prevTickets]);
  };

  const handleTicketUpdated = (updatedTicket: Ticket) => {
    setTickets(prevTickets => 
      prevTickets.map(ticket => 
        ticket.id === updatedTicket.id ? updatedTicket : ticket
      )
    );
  };

  const handleViewTicket = (ticket: Ticket) => {
    setSelectedTicket(ticket);
  };

  return (
    <div className="space-y-6">
      {/* Header Actions */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex-1 max-w-md">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search tickets..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0066FF] focus:border-transparent"
            />
          </div>
        </div>
        
        <button
          onClick={() => setIsModalOpen(true)}
          className="inline-flex items-center px-4 py-2 bg-[#0066FF] text-white rounded-lg hover:bg-[#0052cc] transition-colors"
        >
          <Plus className="h-4 w-4 mr-2" />
          New Ticket
        </button>
      </div>
      
      {/* Filters - Categories */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() => setSelectedCategory('all')}
          className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
            selectedCategory === 'all'
              ? 'bg-[#0066FF] text-white'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          }`}
        >
          All Categories
        </button>
        {Object.keys(categoryColors).map(cat => (
          <button
            key={cat}
            onClick={() => setSelectedCategory(cat)}
            className={`px-3 py-1.5 text-sm rounded-lg transition-colors capitalize ${
              selectedCategory === cat
                ? 'bg-[#0066FF] text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            {cat}
          </button>
        ))}
      </div>
      
      {/* Filters - Status */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() => setSelectedStatus('all')}
          className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
            selectedStatus === 'all'
              ? 'bg-[#0066FF] text-white'
              : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
          }`}
        >
          All Status
        </button>
        {Object.keys(statusColors).map(status => (
          <button
            key={status}
            onClick={() => setSelectedStatus(status)}
            className={`px-3 py-1.5 text-sm rounded-lg transition-colors capitalize ${
              selectedStatus === status
                ? 'bg-[#0066FF] text-white'
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            {status.replace('_', ' ')}
          </button>
        ))}
      </div>
      
      {/* Tickets List */}
      {filteredTickets.length === 0 ? (
        <div className="bg-white rounded-2xl border border-gray-200 p-12 text-center">
          <MessageCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No tickets found</h3>
          <p className="text-gray-500 mb-4">
            {searchTerm || selectedCategory !== 'all' || selectedStatus !== 'all'
              ? "No tickets match your filters"
              : "You haven't created any support tickets yet"}
          </p>
          <button
            onClick={() => setIsModalOpen(true)}
            className="inline-flex items-center px-4 py-2 bg-[#0066FF] text-white rounded-lg hover:bg-[#0052cc] transition-colors"
          >
            <Plus className="h-4 w-4 mr-2" />
            Create Your First Ticket
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {filteredTickets.map((ticket) => (
            <TicketCard key={ticket.id} ticket={ticket} onView={handleViewTicket} />
          ))}
        </div>
      )}
      
      {/* Modals */}
      <NewTicketModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSuccess={handleTicketCreated}
      />
      
      {selectedTicket && (
        <TicketDetailModal
          ticket={selectedTicket}
          onClose={() => setSelectedTicket(null)}
          onUpdate={handleTicketUpdated}
        />
      )}
    </div>
  );
}