import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { X, User, Send, MessageSquare, Clock, AlertCircle, Mail } from 'lucide-react';
import { Ticket, TicketComment, TicketStatus, TicketPriority, TicketCategory, TicketType } from '../types';
import { useCreateTicket, useUpdateTicket, useTicketComments, useCreateTicketComment } from '../hooks/useTickets';
import { useStaffForAssignment, usePlatformStaffForAssignment } from '../hooks/useUsers';
import { useQueryClient } from '@tanstack/react-query';
import { useSandbox } from '../contexts/SandboxContext';
import { useCurrentUser } from '../hooks/useAuth';

interface TicketModalProps {
  ticket?: Ticket | null; // If provided, it's an edit/detail view
  onClose: () => void;
  defaultTicketType?: TicketType; // Allow specifying default ticket type
}

// Category options grouped by ticket type
const CATEGORY_OPTIONS: Record<TicketType, TicketCategory[]> = {
  PLATFORM: ['BILLING', 'TECHNICAL', 'FEATURE_REQUEST', 'ACCOUNT', 'OTHER'],
  CUSTOMER: ['APPOINTMENT', 'REFUND', 'COMPLAINT', 'GENERAL_INQUIRY', 'OTHER'],
  STAFF_REQUEST: ['TIME_OFF', 'SCHEDULE_CHANGE', 'EQUIPMENT', 'OTHER'],
  INTERNAL: ['EQUIPMENT', 'GENERAL_INQUIRY', 'OTHER'],
};

const TicketModal: React.FC<TicketModalProps> = ({ ticket, onClose, defaultTicketType = 'CUSTOMER' }) => {
  const { t } = useTranslation();
  const queryClient = useQueryClient();
  const { isSandbox } = useSandbox();
  const { data: currentUser } = useCurrentUser();
  const [subject, setSubject] = useState(ticket?.subject || '');
  const [description, setDescription] = useState(ticket?.description || '');
  const [priority, setPriority] = useState<TicketPriority>(ticket?.priority || 'MEDIUM');
  const [category, setCategory] = useState<TicketCategory>(ticket?.category || 'OTHER');
  const [ticketType, setTicketType] = useState<TicketType>(ticket?.ticketType || defaultTicketType);
  const [assigneeId, setAssigneeId] = useState<string | undefined>(ticket?.assignee);
  const [status, setStatus] = useState<TicketStatus>(ticket?.status || 'OPEN');
  const [replyText, setReplyText] = useState('');
  const [internalNoteText, setInternalNoteText] = useState('');

  // Check if user is a platform admin (superuser or platform_manager)
  const isPlatformAdmin = currentUser?.role && ['superuser', 'platform_manager'].includes(currentUser.role);
  const isPlatformStaff = currentUser?.role && ['superuser', 'platform_manager', 'platform_support'].includes(currentUser.role);

  // Check if this is a platform ticket in sandbox mode (should be disabled)
  const isPlatformTicketInSandbox = ticketType === 'PLATFORM' && isSandbox;

  // Fetch users for assignee dropdown - use platform staff for platform tickets
  const { data: businessUsers = [] } = useStaffForAssignment();
  const { data: platformUsers = [] } = usePlatformStaffForAssignment();

  // Use platform staff for PLATFORM tickets, business staff otherwise
  const users = ticketType === 'PLATFORM' ? platformUsers : businessUsers;

  // Fetch comments for the ticket if in detail/edit mode
  const { data: comments, isLoading: isLoadingComments } = useTicketComments(ticket?.id);

  // Mutations
  const createTicketMutation = useCreateTicket();
  const updateTicketMutation = useUpdateTicket();
  const createCommentMutation = useCreateTicketComment();

  // Get available categories based on ticket type
  const availableCategories = CATEGORY_OPTIONS[ticketType] || CATEGORY_OPTIONS.CUSTOMER;

  useEffect(() => {
    if (ticket) {
      setSubject(ticket.subject);
      setDescription(ticket.description);
      setPriority(ticket.priority);
      setCategory(ticket.category || 'OTHER');
      setTicketType(ticket.ticketType);
      setAssigneeId(ticket.assignee);
      setStatus(ticket.status);
    } else {
      // Reset form for new ticket creation
      setSubject('');
      setDescription('');
      setPriority('MEDIUM');
      setCategory('OTHER');
      setTicketType(defaultTicketType);
      setAssigneeId(undefined);
      setStatus('OPEN');
    }
  }, [ticket, defaultTicketType]);

  // Reset category when ticket type changes (if current category not available)
  useEffect(() => {
    if (!availableCategories.includes(category)) {
      setCategory('OTHER');
    }
  }, [ticketType, availableCategories, category]);

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

    const ticketData = {
      subject,
      description,
      priority,
      category,
      assignee: assigneeId,
      status,
      ticketType,
    };

    if (ticket) {
      await updateTicketMutation.mutateAsync({ id: ticket.id, updates: ticketData });
    } else {
      await createTicketMutation.mutateAsync(ticketData);
    }
    onClose();
  };

  const handleAddReply = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!ticket?.id || !replyText.trim()) return;

    const commentData: Partial<TicketComment> = {
      commentText: replyText.trim(),
      isInternal: false,
    };

    await createCommentMutation.mutateAsync({ ticketId: ticket.id, commentData });
    setReplyText('');
    queryClient.invalidateQueries({ queryKey: ['ticketComments', ticket.id] });
  };

  const handleAddInternalNote = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!ticket?.id || !internalNoteText.trim()) return;

    const commentData: Partial<TicketComment> = {
      commentText: internalNoteText.trim(),
      isInternal: true,
    };

    await createCommentMutation.mutateAsync({ ticketId: ticket.id, commentData });
    setInternalNoteText('');
    queryClient.invalidateQueries({ queryKey: ['ticketComments', ticket.id] });
  };
  
  const statusOptions: TicketStatus[] = ['OPEN', 'IN_PROGRESS', 'AWAITING_RESPONSE', 'RESOLVED', 'CLOSED'];
  const priorityOptions: TicketPriority[] = ['LOW', 'MEDIUM', 'HIGH', 'URGENT'];
  const ticketTypeOptions: TicketType[] = ['CUSTOMER', 'STAFF_REQUEST', 'INTERNAL', 'PLATFORM'];

  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-3xl max-h-[90vh] overflow-hidden flex flex-col" onClick={e => e.stopPropagation()}>
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
            {ticket ? t('tickets.ticketDetails') : t('tickets.newTicket')}
          </h3>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300 p-1 rounded-full">
            <X size={20} />
          </button>
        </div>

        {/* Sandbox Warning for Platform Tickets */}
        {isPlatformTicketInSandbox && (
          <div className="mx-6 mt-4 p-4 bg-red-50 dark:bg-red-900/20 border-2 border-red-500 dark:border-red-600 rounded-lg">
            <div className="flex items-start gap-3">
              <AlertCircle size={20} className="text-red-600 dark:text-red-400 flex-shrink-0 mt-0.5" />
              <div>
                <h4 className="text-sm font-semibold text-red-800 dark:text-red-200">
                  {t('tickets.sandboxRestriction', 'Platform Support Unavailable in Test Mode')}
                </h4>
                <p className="text-sm text-red-700 dark:text-red-300 mt-1">
                  {t('tickets.sandboxRestrictionMessage', 'You can only contact SmoothSchedule support in live mode. Please switch to live mode to create a support ticket.')}
                </p>
              </div>
            </div>
          </div>
        )}

        {/* Form / Details */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          <form onSubmit={handleSubmitTicket} className="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)}
                className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 disabled:opacity-50 disabled:cursor-not-allowed"
                required
                disabled={isPlatformTicketInSandbox || (!!ticket && !createTicketMutation.isPending && !updateTicketMutation.isPending)} // Disable in sandbox or if viewing existing
              />
            </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={4}
                className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 disabled:opacity-50 disabled:cursor-not-allowed"
                required
                disabled={isPlatformTicketInSandbox || (!!ticket && !createTicketMutation.isPending && !updateTicketMutation.isPending)} // Disable in sandbox or if viewing existing
              />
            </div>

            {/* Ticket Type (only for new tickets, and hide for platform tickets) */}
            {!ticket && ticketType !== 'PLATFORM' && (
              <div>
                <label htmlFor="ticketType" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  {t('tickets.ticketType')}
                </label>
                <select
                  id="ticketType"
                  value={ticketType}
                  onChange={(e) => setTicketType(e.target.value as TicketType)}
                  className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                >
                  {ticketTypeOptions.map(opt => (
                    <option key={opt} value={opt}>{t(`tickets.types.${opt.toLowerCase()}`)}</option>
                  ))}
                </select>
              </div>
            )}

            {/* Priority & Category - Show for non-PLATFORM tickets OR platform admins viewing PLATFORM tickets */}
            {(ticketType !== 'PLATFORM' || isPlatformAdmin) && (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <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-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={!!ticket && !isPlatformAdmin && !createTicketMutation.isPending && !updateTicketMutation.isPending}
                  >
                    {priorityOptions.map(opt => (
                      <option key={opt} value={opt}>{t(`tickets.priorities.${opt.toLowerCase()}`)}</option>
                    ))}
                  </select>
                </div>
                <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-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={!!ticket && !isPlatformAdmin && !createTicketMutation.isPending && !updateTicketMutation.isPending}
                  >
                    {availableCategories.map(cat => (
                      <option key={cat} value={cat}>{t(`tickets.categories.${cat.toLowerCase()}`)}</option>
                    ))}
                  </select>
                </div>
              </div>
            )}

            {/* External Email Info - Show for platform tickets from external senders */}
            {ticket && ticketType === 'PLATFORM' && isPlatformStaff && ticket.externalEmail && (
              <div className="p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                <div className="flex items-center gap-2 text-sm text-blue-800 dark:text-blue-200">
                  <Mail size={16} />
                  <span className="font-medium">{t('tickets.externalSender', 'External Sender')}:</span>
                  <span>{ticket.externalName ? `${ticket.externalName} <${ticket.externalEmail}>` : ticket.externalEmail}</span>
                </div>
              </div>
            )}

            {/* Assignee & Status - Show for existing tickets (non-PLATFORM OR platform admins viewing PLATFORM) */}
            {ticket && (ticketType !== 'PLATFORM' || isPlatformAdmin) && (
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="assignee" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('tickets.assignee')}
                  </label>
                  <select
                    id="assignee"
                    value={assigneeId || ''}
                    onChange={(e) => setAssigneeId(e.target.value || undefined)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                  >
                    <option value="">{t('tickets.unassigned')}</option>
                    {users.map(user => (
                      <option key={user.id} value={user.id}>{user.name}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label htmlFor="status" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    {t('tickets.status')}
                  </label>
                  <select
                    id="status"
                    value={status}
                    onChange={(e) => setStatus(e.target.value as TicketStatus)}
                    className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                  >
                    {statusOptions.map(opt => (
                      <option key={opt} value={opt}>{t(`tickets.status.${opt.toLowerCase()}`)}</option>
                    ))}
                  </select>
                </div>
              </div>
            )}

            {/* Submit Button for Ticket */}
            {!ticket && ( // Only show submit for new tickets
              <div className="flex justify-end pt-4 border-t border-gray-200 dark:border-gray-700">
                {isPlatformTicketInSandbox ? (
                  <button
                    type="button"
                    onClick={onClose}
                    className="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                  >
                    {t('common.cancel', 'Cancel')}
                  </button>
                ) : (
                  <button
                    type="submit"
                    className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors"
                    disabled={createTicketMutation.isPending}
                  >
                    {createTicketMutation.isPending ? t('common.saving') : t('tickets.createTicket')}
                  </button>
                )}
              </div>
            )}
            {ticket && (ticketType !== 'PLATFORM' || isPlatformAdmin) && ( // Show update button for existing tickets (non-PLATFORM OR platform admins)
              <div className="flex justify-end pt-4 border-t border-gray-200 dark:border-gray-700">
                <button
                  type="submit"
                  className="px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors"
                  disabled={updateTicketMutation.isPending}
                >
                  {updateTicketMutation.isPending ? t('common.saving') : t('tickets.updateTicket')}
                </button>
              </div>
            )}
          </form>

          {/* Comments Section */}
          {ticket && (
            <div className="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700 space-y-4">
              <h4 className="text-md font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <MessageSquare size={18} className="text-brand-500" /> {t('tickets.comments')}
              </h4>
              {isLoadingComments ? (
                <div className="text-center text-gray-500 dark:text-gray-400">{t('common.loading')}</div>
              ) : comments && comments.length > 0 ? (
                <div className="space-y-4 max-h-60 overflow-y-auto custom-scrollbar pr-2">
                  {comments.map((comment) => (
                    <div key={comment.id} className="bg-gray-50 dark:bg-gray-700 rounded-lg p-3 shadow-sm">
                      <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
                        <div className="flex items-center gap-1">
                          <User size={12} />
                          <span>{comment.authorFullName || comment.authorEmail}</span>
                          {comment.isInternal && <span className="ml-2 px-1.5 py-0.5 rounded-full bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300 text-[10px]">{t('tickets.internal')}</span>}
                        </div>
                        <Clock size={12} className="inline-block mr-1" />
                        <span>{new Date(comment.createdAt).toLocaleString()}</span>
                      </div>
                      <p className="mt-2 text-sm text-gray-700 dark:text-gray-200">{comment.commentText}</p>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-gray-500 dark:text-gray-400 text-sm">{t('tickets.noComments')}</p>
              )}

              {/* Reply Form */}
              <form onSubmit={handleAddReply} className="pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {t('tickets.replyLabel', 'Reply to Customer')}
                </label>
                <textarea
                  value={replyText}
                  onChange={(e) => setReplyText(e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                  placeholder={t('tickets.addCommentPlaceholder')}
                />
                <div className="flex justify-end">
                  <button
                    type="submit"
                    className="flex items-center gap-2 px-4 py-2 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors"
                    disabled={createCommentMutation.isPending || !replyText.trim()}
                  >
                    <Send size={16} /> {createCommentMutation.isPending ? t('common.sending') : t('tickets.postComment')}
                  </button>
                </div>
              </form>

              {/* Internal Note Form - Show for non-PLATFORM tickets OR platform staff viewing PLATFORM tickets */}
              {(ticketType !== 'PLATFORM' || isPlatformStaff) && (
                <form onSubmit={handleAddInternalNote} className="pt-4 border-t border-gray-200 dark:border-gray-700 space-y-3">
                  <label className="block text-sm font-medium text-orange-600 dark:text-orange-400">
                    {t('tickets.internalNoteLabel', 'Internal Note')}
                    <span className="ml-2 text-xs font-normal text-gray-500 dark:text-gray-400">
                      {t('tickets.internalNoteHint', '(Not visible to customer)')}
                    </span>
                  </label>
                  <textarea
                    value={internalNoteText}
                    onChange={(e) => setInternalNoteText(e.target.value)}
                    rows={2}
                    className="w-full px-3 py-2 rounded-lg border border-orange-300 dark:border-orange-600 bg-orange-50 dark:bg-orange-900/20 text-gray-900 dark:text-white focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                    placeholder={t('tickets.internalNotePlaceholder', 'Add an internal note...')}
                  />
                  <div className="flex justify-end">
                    <button
                      type="submit"
                      className="flex items-center gap-2 px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition-colors"
                      disabled={createCommentMutation.isPending || !internalNoteText.trim()}
                    >
                      <Send size={16} /> {createCommentMutation.isPending ? t('common.sending') : t('tickets.addNote', 'Add Note')}
                    </button>
                  </div>
                </form>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TicketModal;