import React, { useState } from 'react';
import { useOutletContext } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { User, Business, Ticket, TicketComment, TicketStatus, TicketPriority, TicketCategory } from '../../types';
import { useTickets, useCreateTicket, useTicketComments, useCreateTicketComment } from '../../hooks/useTickets';
import { MessageSquare, Plus, Clock, CheckCircle, AlertCircle, HelpCircle, ChevronRight, Send, User as UserIcon } from 'lucide-react';

// Status badge component
const StatusBadge: React.FC<{ status: TicketStatus }> = ({ status }) => {
  const { t } = useTranslation();
  const statusConfig: Record<TicketStatus, { color: string; icon: React.ReactNode }> = {
    OPEN: { color: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300', icon: <AlertCircle size={12} /> },
    IN_PROGRESS: { color: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300', icon: <Clock size={12} /> },
    AWAITING_RESPONSE: { color: 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300', icon: <HelpCircle size={12} /> },
    RESOLVED: { color: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300', icon: <CheckCircle size={12} /> },
    CLOSED: { color: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300', icon: <CheckCircle size={12} /> },
  };

  const config = statusConfig[status];
  return (
    <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${config.color}`}>
      {config.icon}
      {t(`tickets.status.${status.toLowerCase()}`)}
    </span>
  );
};

// Priority badge component
const PriorityBadge: React.FC<{ priority: TicketPriority }> = ({ priority }) => {
  const { t } = useTranslation();
  const priorityConfig: Record<TicketPriority, string> = {
    LOW: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',
    MEDIUM: 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400',
    HIGH: 'bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400',
    URGENT: 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400',
  };

  return (
    <span className={`px-2 py-1 rounded-full text-xs font-medium ${priorityConfig[priority]}`}>
      {t(`tickets.priorities.${priority.toLowerCase()}`)}
    </span>
  );
};

// New ticket form component
const NewTicketForm: React.FC<{ onClose: () => void; onSuccess: () => void }> = ({ onClose, onSuccess }) => {
  const { t } = useTranslation();
  const [subject, setSubject] = useState('');
  const [description, setDescription] = useState('');
  const [category, setCategory] = useState<TicketCategory>('GENERAL_INQUIRY');
  const [priority, setPriority] = useState<TicketPriority>('MEDIUM');

  const createTicketMutation = useCreateTicket();

  const categoryOptions: TicketCategory[] = ['APPOINTMENT', 'REFUND', 'COMPLAINT', 'GENERAL_INQUIRY', 'OTHER'];
  const priorityOptions: TicketPriority[] = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    await createTicketMutation.mutateAsync({
      subject,
      description,
      category,
      priority,
      ticketType: 'CUSTOMER',
    });

    onSuccess();
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" onClick={onClose}>
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl w-full max-w-lg" onClick={e => e.stopPropagation()}>
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            {t('customerSupport.newRequest', 'Submit a Support Request')}
          </h3>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {/* Subject */}
          <div>
            <label htmlFor="subject" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('tickets.subject')}
            </label>
            <input
              type="text"
              id="subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder={t('customerSupport.subjectPlaceholder', 'Brief summary of your issue')}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
              required
            />
          </div>

          {/* Category */}
          <div>
            <label htmlFor="category" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('tickets.category')}
            </label>
            <select
              id="category"
              value={category}
              onChange={(e) => setCategory(e.target.value as TicketCategory)}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
            >
              {categoryOptions.map(cat => (
                <option key={cat} value={cat}>{t(`tickets.categories.${cat.toLowerCase()}`)}</option>
              ))}
            </select>
          </div>

          {/* Priority */}
          <div>
            <label htmlFor="priority" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('tickets.priority')}
            </label>
            <select
              id="priority"
              value={priority}
              onChange={(e) => setPriority(e.target.value as TicketPriority)}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
            >
              {priorityOptions.map(opt => (
                <option key={opt} value={opt}>{t(`tickets.priorities.${opt.toLowerCase()}`)}</option>
              ))}
            </select>
          </div>

          {/* Description */}
          <div>
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t('tickets.description')}
            </label>
            <textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={5}
              placeholder={t('customerSupport.descriptionPlaceholder', 'Please describe your issue in detail...')}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
              required
            />
          </div>

          {/* Actions */}
          <div className="flex justify-end gap-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
            >
              {t('common.cancel')}
            </button>
            <button
              type="submit"
              disabled={createTicketMutation.isPending}
              className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors disabled:opacity-50"
            >
              {createTicketMutation.isPending ? t('common.saving') : t('customerSupport.submitRequest', 'Submit Request')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

// Ticket detail view
const TicketDetail: React.FC<{ ticket: Ticket; onBack: () => void }> = ({ ticket, onBack }) => {
  const { t } = useTranslation();
  const [replyText, setReplyText] = useState('');

  // Fetch comments for this ticket
  const { data: comments = [], isLoading: isLoadingComments } = useTicketComments(ticket.id);
  const createCommentMutation = useCreateTicketComment();

  // Filter out internal comments (customers shouldn't see them)
  const visibleComments = comments.filter((comment: TicketComment) => !comment.isInternal);

  const handleSubmitReply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!replyText.trim()) return;

    await createCommentMutation.mutateAsync({
      ticketId: ticket.id,
      commentData: {
        commentText: replyText.trim(),
        isInternal: false, // Customer replies are never internal
      },
    });
    setReplyText('');
  };

  const isTicketClosed = ticket.status === 'CLOSED';

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={onBack}
          className="text-sm text-brand-600 hover:text-brand-700 dark:text-brand-400 mb-2 flex items-center gap-1"
        >
          &larr; {t('common.back', 'Back to tickets')}
        </button>
        <div className="flex items-start justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{ticket.subject}</h2>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              {t('tickets.ticketNumber', 'Ticket #{{number}}', { number: ticket.ticketNumber })}
              {' • '}
              {t('tickets.createdAt', 'Created {{date}}', { date: new Date(ticket.createdAt).toLocaleDateString() })}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <StatusBadge status={ticket.status} />
            <PriorityBadge priority={ticket.priority} />
          </div>
        </div>
      </div>

      {/* Description */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">{t('tickets.description')}</h3>
        <p className="text-gray-900 dark:text-white whitespace-pre-wrap">{ticket.description}</p>
      </div>

      {/* Status message */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/50">
        {ticket.status === 'OPEN' && (
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('customerSupport.statusOpen', 'Your request has been received. Our team will review it shortly.')}
          </p>
        )}
        {ticket.status === 'IN_PROGRESS' && (
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('customerSupport.statusInProgress', 'Our team is currently working on your request.')}
          </p>
        )}
        {ticket.status === 'AWAITING_RESPONSE' && (
          <p className="text-sm text-yellow-600 dark:text-yellow-400">
            {t('customerSupport.statusAwaitingResponse', 'We need additional information from you. Please reply below.')}
          </p>
        )}
        {ticket.status === 'RESOLVED' && (
          <p className="text-sm text-green-600 dark:text-green-400">
            {t('customerSupport.statusResolved', 'Your request has been resolved. Thank you for contacting us!')}
          </p>
        )}
        {ticket.status === 'CLOSED' && (
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('customerSupport.statusClosed', 'This ticket has been closed.')}
          </p>
        )}
      </div>

      {/* Comments / Conversation */}
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
        <h3 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-4 flex items-center gap-2">
          <MessageSquare size={16} />
          {t('customerSupport.conversation', 'Conversation')}
        </h3>

        {isLoadingComments ? (
          <div className="text-center py-4 text-gray-500 dark:text-gray-400">
            {t('common.loading')}
          </div>
        ) : visibleComments.length === 0 ? (
          <p className="text-sm text-gray-500 dark:text-gray-400 py-4">
            {t('customerSupport.noRepliesYet', 'No replies yet. Our team will respond soon.')}
          </p>
        ) : (
          <div className="space-y-4 max-h-96 overflow-y-auto">
            {visibleComments.map((comment: TicketComment) => (
              <div key={comment.id} className="bg-gray-50 dark:bg-gray-700/50 rounded-lg p-4">
                <div className="flex items-center justify-between mb-2">
                  <div className="flex items-center gap-2 text-sm">
                    <div className="w-8 h-8 rounded-full bg-brand-100 dark:bg-brand-900/30 flex items-center justify-center">
                      <UserIcon size={14} className="text-brand-600 dark:text-brand-400" />
                    </div>
                    <span className="font-medium text-gray-900 dark:text-white">
                      {comment.authorFullName || comment.authorEmail}
                    </span>
                  </div>
                  <span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-1">
                    <Clock size={12} />
                    {new Date(comment.createdAt).toLocaleString()}
                  </span>
                </div>
                <p className="text-gray-700 dark:text-gray-300 whitespace-pre-wrap pl-10">
                  {comment.commentText}
                </p>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Reply Form */}
      {!isTicketClosed ? (
        <div className="px-6 py-4">
          <form onSubmit={handleSubmitReply} className="space-y-3">
            <label htmlFor="reply" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              {t('customerSupport.yourReply', 'Your Reply')}
            </label>
            <textarea
              id="reply"
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              rows={4}
              placeholder={t('customerSupport.replyPlaceholder', 'Type your message here...')}
              className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
              disabled={createCommentMutation.isPending}
            />
            <div className="flex justify-end">
              <button
                type="submit"
                disabled={createCommentMutation.isPending || !replyText.trim()}
                className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Send size={16} />
                {createCommentMutation.isPending
                  ? t('common.sending', 'Sending...')
                  : t('customerSupport.sendReply', 'Send Reply')}
              </button>
            </div>
          </form>
        </div>
      ) : (
        <div className="px-6 py-4 bg-gray-50 dark:bg-gray-900/50 text-center">
          <p className="text-sm text-gray-500 dark:text-gray-400">
            {t('customerSupport.ticketClosedNoReply', 'This ticket is closed. If you need further assistance, please open a new support request.')}
          </p>
        </div>
      )}
    </div>
  );
};

const CustomerSupport: React.FC = () => {
  const { t } = useTranslation();
  const { user, business } = useOutletContext<{ user: User; business: Business }>();
  const [showNewTicketForm, setShowNewTicketForm] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);

  const { data: tickets = [], isLoading, refetch } = useTickets();

  // Filter to only show customer's own tickets
  const myTickets = tickets.filter(ticket => ticket.ticketType === 'CUSTOMER');

  if (selectedTicket) {
    return (
      <div className="max-w-4xl mx-auto">
        <TicketDetail ticket={selectedTicket} onBack={() => setSelectedTicket(null)} />
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {t('customerSupport.title', 'Support')}
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {t('customerSupport.subtitle', 'Get help with your appointments and account')}
          </p>
        </div>
        <button
          onClick={() => setShowNewTicketForm(true)}
          className="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('customerSupport.newRequest', 'New Request')}
        </button>
      </div>

      {/* Quick Help Section */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-8">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          {t('customerSupport.quickHelp', 'Quick Help')}
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <a
            href="#"
            onClick={(e) => { e.preventDefault(); setShowNewTicketForm(true); }}
            className="flex items-center gap-3 p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
          >
            <div className="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
              <MessageSquare size={20} className="text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">
                {t('customerSupport.contactUs', 'Contact Us')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('customerSupport.contactUsDesc', 'Submit a support request')}
              </p>
            </div>
          </a>
          <a
            href={`mailto:support@${business?.subdomain || 'business'}.smoothschedule.com`}
            className="flex items-center gap-3 p-4 rounded-lg border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
          >
            <div className="w-10 h-10 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <HelpCircle size={20} className="text-green-600 dark:text-green-400" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">
                {t('customerSupport.emailUs', 'Email Us')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('customerSupport.emailUsDesc', 'Get help via email')}
              </p>
            </div>
          </a>
        </div>
      </div>

      {/* My Requests */}
      <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white">
            {t('customerSupport.myRequests', 'My Support Requests')}
          </h2>
        </div>

        {isLoading ? (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400">
            {t('common.loading')}
          </div>
        ) : myTickets.length === 0 ? (
          <div className="p-8 text-center">
            <MessageSquare size={48} className="mx-auto text-gray-300 dark:text-gray-600 mb-4" />
            <p className="text-gray-500 dark:text-gray-400">
              {t('customerSupport.noRequests', "You haven't submitted any support requests yet.")}
            </p>
            <button
              onClick={() => setShowNewTicketForm(true)}
              className="mt-4 text-brand-600 hover:text-brand-700 dark:text-brand-400 font-medium"
            >
              {t('customerSupport.submitFirst', 'Submit your first request')}
            </button>
          </div>
        ) : (
          <div className="divide-y divide-gray-200 dark:divide-gray-700">
            {myTickets.map((ticket) => (
              <button
                key={ticket.id}
                onClick={() => setSelectedTicket(ticket)}
                className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors text-left"
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-3 mb-1">
                    <h3 className="font-medium text-gray-900 dark:text-white truncate">
                      {ticket.subject}
                    </h3>
                    <StatusBadge status={ticket.status} />
                  </div>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    {t('tickets.ticketNumber', 'Ticket #{{number}}', { number: ticket.ticketNumber })}
                    {' • '}
                    {new Date(ticket.createdAt).toLocaleDateString()}
                  </p>
                </div>
                <ChevronRight size={20} className="text-gray-400 flex-shrink-0 ml-4" />
              </button>
            ))}
          </div>
        )}
      </div>

      {/* New Ticket Modal */}
      {showNewTicketForm && (
        <NewTicketForm
          onClose={() => setShowNewTicketForm(false)}
          onSuccess={() => refetch()}
        />
      )}
    </div>
  );
};

export default CustomerSupport;
