import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Ticket, TicketComment, TicketStatus, TicketPriority, TicketCategory } from '../types';
import { useTickets, useTicketComments, useCreateTicketComment } from '../hooks/useTickets';
import { MessageSquare, Plus, Clock, CheckCircle, AlertCircle, HelpCircle, ChevronRight, Send, User as UserIcon, BookOpen, Code, LifeBuoy } from 'lucide-react';
import TicketModal from '../components/TicketModal';
import { useSandbox } from '../contexts/SandboxContext';

// 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>
  );
};

// Ticket detail view (read-only for business users viewing platform tickets)
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 (business users shouldn't see platform's internal notes)
  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, // Business 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 support 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('platformSupport.statusOpen', 'Your request has been received. Our support team will review it shortly.')}
          </p>
        )}
        {ticket.status === 'IN_PROGRESS' && (
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('platformSupport.statusInProgress', 'Our support team is currently working on your request.')}
          </p>
        )}
        {ticket.status === 'AWAITING_RESPONSE' && (
          <p className="text-sm text-yellow-600 dark:text-yellow-400">
            {t('platformSupport.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('platformSupport.statusResolved', 'Your request has been resolved. Thank you for contacting SmoothSchedule support!')}
          </p>
        )}
        {ticket.status === 'CLOSED' && (
          <p className="text-sm text-gray-600 dark:text-gray-400">
            {t('platformSupport.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('platformSupport.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('platformSupport.noRepliesYet', 'No replies yet. Our support 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('platformSupport.yourReply', 'Your Reply')}
            </label>
            <textarea
              id="reply"
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              rows={4}
              placeholder={t('platformSupport.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('platformSupport.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('platformSupport.ticketClosedNoReply', 'This ticket is closed. If you need further assistance, please open a new support request.')}
          </p>
        </div>
      )}
    </div>
  );
};

const PlatformSupport: React.FC = () => {
  const { t } = useTranslation();
  const { isSandbox } = useSandbox();
  const [showNewTicketModal, setShowNewTicketModal] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<Ticket | null>(null);

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

  // Filter to only show platform support tickets
  const platformTickets = tickets.filter(ticket => ticket.ticketType === 'PLATFORM');

  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('platformSupport.title', 'SmoothSchedule Support')}
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            {t('platformSupport.subtitle', 'Get help from the SmoothSchedule team')}
          </p>
        </div>
        <button
          onClick={() => setShowNewTicketModal(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('platformSupport.newRequest', 'Contact Support')}
        </button>
      </div>

      {/* Sandbox Warning Banner */}
      {isSandbox && (
        <div className="mb-6 p-4 bg-orange-50 dark:bg-orange-900/20 border-2 border-orange-500 dark:border-orange-600 rounded-lg">
          <div className="flex items-start gap-3">
            <AlertCircle size={20} className="text-orange-600 dark:text-orange-400 flex-shrink-0 mt-0.5" />
            <div>
              <h4 className="text-sm font-semibold text-orange-800 dark:text-orange-200">
                {t('platformSupport.sandboxWarning', 'You are in Test Mode')}
              </h4>
              <p className="text-sm text-orange-700 dark:text-orange-300 mt-1">
                {t('platformSupport.sandboxWarningMessage', 'Platform support is only available in Live Mode. Switch to Live Mode to contact SmoothSchedule support.')}
              </p>
            </div>
          </div>
        </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('platformSupport.quickHelp', 'Quick Help')}
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <Link
            to="/help/guide"
            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">
              <BookOpen size={20} className="text-blue-600 dark:text-blue-400" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">
                {t('platformSupport.platformGuide', 'Platform Guide')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('platformSupport.platformGuideDesc', 'Learn the basics')}
              </p>
            </div>
          </Link>
          <Link
            to="/help/api"
            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-purple-100 dark:bg-purple-900/30 flex items-center justify-center">
              <Code size={20} className="text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">
                {t('platformSupport.apiDocs', 'API Docs')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('platformSupport.apiDocsDesc', 'Integration help')}
              </p>
            </div>
          </Link>
          <button
            onClick={() => setShowNewTicketModal(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 text-left"
          >
            <div className="w-10 h-10 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <LifeBuoy size={20} className="text-green-600 dark:text-green-400" />
            </div>
            <div>
              <h3 className="font-medium text-gray-900 dark:text-white">
                {t('platformSupport.contactUs', 'Contact Support')}
              </h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {t('platformSupport.contactUsDesc', 'Get personalized help')}
              </p>
            </div>
          </button>
        </div>
      </div>

      {/* My Support 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('platformSupport.myRequests', 'My Support Requests')}
          </h2>
        </div>

        {isLoading ? (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400">
            {t('common.loading')}
          </div>
        ) : platformTickets.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('platformSupport.noRequests', "You haven't submitted any support requests yet.")}
            </p>
            <button
              onClick={() => setShowNewTicketModal(true)}
              className="mt-4 text-brand-600 hover:text-brand-700 dark:text-brand-400 font-medium"
            >
              {t('platformSupport.submitFirst', 'Submit your first request')}
            </button>
          </div>
        ) : (
          <div className="divide-y divide-gray-200 dark:divide-gray-700">
            {platformTickets.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 */}
      {showNewTicketModal && (
        <TicketModal
          onClose={() => {
            setShowNewTicketModal(false);
            refetch();
          }}
          defaultTicketType="PLATFORM"
        />
      )}
    </div>
  );
};

export default PlatformSupport;
