// app/components/admin/support/SupportTicketDetailModal.tsx
'use client';

import { useState, useEffect, useCallback } from 'react';
import { X, Clock, Save } from 'lucide-react';
import toast from 'react-hot-toast';

interface Reply {
  id: string;
  ticket_id: string;
  user_id: string;
  admin_id: string;
  is_admin: boolean;
  message: string;
  user_name: string;
  user_email: string;
  created_at: string;
}

interface SupportTicket {
  id: string;
  ticket_number: string;
  user_id: string;
  user_name: string;
  user_email: string;
  subject: string;
  category: string;
  priority: string;
  status: string;
  message: string;
  created_at: string;
  updated_at: string;
}

interface SupportTicketDetailModalProps {
  isOpen: boolean;
  onClose: () => void;
  ticket: SupportTicket;
  onUpdate: () => void;
  canReply: boolean;
  canUpdateStatus: boolean;
}

const categoryLabels: Record<string, string> = {
  order: 'Order Related',
  payment: 'Payment Issue',
  technical: 'Technical Problem',
  website: 'Website Related',
  other: 'Other',
};

const priorityColors: Record<string, string> = {
  low: 'bg-var-surface-hover text-var-text-muted',
  medium: 'bg-var-primary-muted text-var-primary-text',
  high: 'bg-var-warning-bg text-var-warning-text',
  urgent: 'bg-var-danger-bg text-var-danger-text',
};

const statusColors: Record<string, string> = {
  open: 'bg-var-warning-bg text-var-warning-text',
  in_progress: 'bg-var-primary-muted text-var-primary-text',
  resolved: 'bg-var-success-bg text-var-success-text',
  closed: 'bg-var-surface-hover text-var-text-muted',
};

export default function SupportTicketDetailModal({
  isOpen,
  onClose,
  ticket,
  onUpdate,
  canReply,
  canUpdateStatus
}: SupportTicketDetailModalProps) {
  const [replies, setReplies] = useState<Reply[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [selectedStatus, setSelectedStatus] = useState(ticket.status);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [loading, setLoading] = useState(true);
  const [isStatusChanged, setIsStatusChanged] = useState(false);
  const [activeTab, setActiveTab] = useState<'details' | 'replies'>('details');

  const fetchReplies = useCallback(async () => {
    try {
      const response = await fetch(`/api/backend/admin/support/tickets/${ticket.id}/replies`);
      const data = await response.json();
      if (response.ok) {
        setReplies(data.replies || []);
      }
    } catch (error) {
      console.error('Error fetching replies:', error);
    } finally {
      setLoading(false);
    }
  }, [ticket.id]);

  // Handle status change
  const handleStatusChange = (newStatus: string) => {
    setSelectedStatus(newStatus);
    setIsStatusChanged(true);
  };

  // Handle submit (status update + reply)
  const handleSubmit = async () => {
    if (!canUpdateStatus && !canReply) {
      toast.error('You do not have permission to update this ticket');
      return;
    }

    setIsSubmitting(true);

    try {
      // 1. Update status if changed
      if (isStatusChanged && canUpdateStatus) {
        const statusResponse = await fetch(`/api/backend/admin/support/tickets/${ticket.id}/status`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ status: selectedStatus }),
        });

        if (!statusResponse.ok) {
          const errorData = await statusResponse.json();
          throw new Error(errorData.error || 'Failed to update status');
        }
        
        toast.success(`Status updated to ${selectedStatus.replace('_', ' ')}`);
      }

      // 2. Send reply if message exists
      if (newMessage.trim() && canReply) {
        const replyResponse = await fetch(`/api/backend/admin/support/tickets/${ticket.id}/replies`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ message: newMessage }),
        });

        if (!replyResponse.ok) {
          const errorData = await replyResponse.json();
          throw new Error(errorData.error || 'Failed to send reply');
        }
        
        toast.success('Reply sent successfully');
        setNewMessage('');
      }

      // 3. Refresh data
      await fetchReplies();
      onUpdate();
      
      // Reset state
      setIsStatusChanged(false);
      
    } catch (error) {
      console.error('Error updating ticket:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to update ticket');
    } finally {
      setIsSubmitting(false);
    }
  };

  useEffect(() => {
    if (isOpen) {
      fetchReplies();
      setSelectedStatus(ticket.status);
      setNewMessage('');
      setIsStatusChanged(false);
      setActiveTab('details');
    }
  }, [isOpen, fetchReplies, ticket.status]);

  if (!isOpen) return null;

  const hasChanges = isStatusChanged || newMessage.trim();
  const canSubmit = (canUpdateStatus || canReply) && hasChanges;
  const unreadCount = replies.filter(r => !r.is_admin).length;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-var-surface rounded-2xl max-w-5xl w-full mx-auto max-h-[90vh] flex flex-col shadow-var-modal">
        {/* Header */}
        <div className="sticky top-0 bg-var-surface border-b border-var-border px-6 py-4 flex justify-between items-start z-10">
          <div className="flex-1">
            <div className="flex items-center gap-3 flex-wrap">
              <h3 className="text-lg font-semibold text-var-text">
                {ticket.subject}
              </h3>
              <span className={`px-2 py-1 rounded-full text-xs font-medium ${priorityColors[ticket.priority]}`}>
                {ticket.priority.toUpperCase()}
              </span>
              <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[selectedStatus]}`}>
                {selectedStatus.replace('_', ' ').toUpperCase()}
              </span>
            </div>
            <div className="flex items-center gap-4 mt-2 flex-wrap">
              <p className="text-sm text-var-text-muted font-mono">#{ticket.ticket_number}</p>
              <p className="text-sm text-var-text-muted">Category: {categoryLabels[ticket.category]}</p>
              <p className="text-sm text-var-text-muted">
                Created: {new Date(ticket.created_at).toLocaleString()}
              </p>
            </div>
          </div>
          <button 
            onClick={onClose} 
            className="text-var-text-muted hover:text-var-text transition-colors p-1 rounded-lg hover:bg-var-surface-hover"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="border-b border-var-border bg-var-surface-hover/50 px-6">
          <div className="flex gap-2">
            <button
              onClick={() => setActiveTab('details')}
              className={`px-4 py-2.5 text-sm font-medium transition-all duration-200 border-b-2 ${
                activeTab === 'details'
                  ? 'border-var-primary text-var-primary'
                  : 'border-transparent text-var-text-muted hover:text-var-text hover:border-var-border'
              }`}
            >
              Ticket Details
            </button>
            <button
              onClick={() => setActiveTab('replies')}
              className={`px-4 py-2.5 text-sm font-medium transition-all duration-200 border-b-2 flex items-center gap-2 ${
                activeTab === 'replies'
                  ? 'border-var-primary text-var-primary'
                  : 'border-transparent text-var-text-muted hover:text-var-text hover:border-var-border'
              }`}
            >
              Conversation
              {unreadCount > 0 && activeTab !== 'replies' && (
                <span className="inline-flex items-center justify-center w-5 h-5 text-xs font-bold text-white bg-var-danger rounded-full">
                  {unreadCount}
                </span>
              )}
            </button>
          </div>
        </div>
        
        {/* Customer Info Bar */}
        <div className="bg-var-surface-hover px-6 py-3 border-b border-var-border">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-var-primary rounded-full flex items-center justify-center shadow-var-card">
              <span className="text-white text-sm font-bold">
                {ticket.user_name?.[0]?.toUpperCase() || 'U'}
              </span>
            </div>
            <div>
              <p className="text-sm font-semibold text-var-text">
                {ticket.user_name || 'Guest User'}
              </p>
              <p className="text-xs text-var-primary">{ticket.user_email}</p>
            </div>
          </div>
        </div>
        
        {/* Content Area */}
        <div className="flex-1 overflow-y-auto p-6">
          {activeTab === 'details' ? (
            <div className="space-y-4">
              {/* Original Ticket Message */}
              <div className="bg-var-surface-hover rounded-xl p-5 border border-var-border">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-var-primary-muted rounded-full flex items-center justify-center">
                      <span className="text-var-primary-text text-sm font-bold">
                        {ticket.user_name?.[0]?.toUpperCase() || 'U'}
                      </span>
                    </div>
                    <span className="font-medium text-var-text">
                      {ticket.user_name || 'Guest User'}
                    </span>
                    <span className="text-xs text-var-text-muted bg-var-surface px-2 py-0.5 rounded-full">Customer</span>
                  </div>
                  <span className="text-xs text-var-text-muted">
                    {new Date(ticket.created_at).toLocaleString()}
                  </span>
                </div>
                <p className="text-var-text whitespace-pre-wrap leading-relaxed">{ticket.message}</p>
              </div>
              
              {/* Ticket Metadata */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-4">
                <div className="bg-var-surface-hover rounded-xl p-3 border border-var-border">
                  <p className="text-xs text-var-text-muted mb-1">Ticket ID</p>
                  <p className="text-sm font-mono font-medium text-var-text">{ticket.ticket_number}</p>
                </div>
                <div className="bg-var-surface-hover rounded-xl p-3 border border-var-border">
                  <p className="text-xs text-var-text-muted mb-1">Priority</p>
                  <p className="text-sm font-medium capitalize text-var-text">{ticket.priority}</p>
                </div>
                <div className="bg-var-surface-hover rounded-xl p-3 border border-var-border">
                  <p className="text-xs text-var-text-muted mb-1">Category</p>
                  <p className="text-sm font-medium text-var-text">{categoryLabels[ticket.category]}</p>
                </div>
                <div className="bg-var-surface-hover rounded-xl p-3 border border-var-border">
                  <p className="text-xs text-var-text-muted mb-1">Total Replies</p>
                  <p className="text-sm font-medium text-var-text">{replies.length}</p>
                </div>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              {loading ? (
                <div className="text-center py-12">
                  <div className="w-10 h-10 border-4 border-var-border border-t-var-primary rounded-full animate-spin mx-auto mb-4" />
                  <p className="text-var-text-muted">Loading conversation...</p>
                </div>
              ) : replies.length === 0 ? (
                <div className="text-center py-12 bg-var-surface-hover rounded-xl border border-var-border">
                  <svg className="w-12 h-12 mx-auto mb-3 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                  </svg>
                  <p className="text-var-text-muted">No replies yet</p>
                  <p className="text-sm text-var-text-muted mt-1">Be the first to respond to this ticket</p>
                </div>
              ) : (
                replies.map((reply, index) => (
                  <div key={reply.id} className={`animate-fade-in-up ${reply.is_admin ? 'ml-0 md:ml-12' : ''}`} style={{ animationDelay: `${index * 50}ms` }}>
                    <div className={`rounded-xl p-4 ${
                      reply.is_admin 
                        ? 'bg-var-primary-muted border border-var-primary' 
                        : 'bg-var-surface-hover border border-var-border'
                    }`}>
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                            reply.is_admin ? 'bg-var-primary' : 'bg-var-surface'
                          }`}>
                            <span className={`text-sm font-bold ${reply.is_admin ? 'text-white' : 'text-var-text'}`}>
                              {reply.is_admin ? 'A' : (reply.user_name?.[0]?.toUpperCase() || 'U')}
                            </span>
                          </div>
                          <span className="font-medium text-var-text">
                            {reply.is_admin ? 'Support Team' : (reply.user_name || 'Customer')}
                          </span>
                          {reply.is_admin && (
                            <span className="text-xs text-var-primary-text font-medium bg-var-surface px-2 py-0.5 rounded-full">
                              Admin
                            </span>
                          )}
                        </div>
                        <span className="text-xs text-var-text-muted">
                          {new Date(reply.created_at).toLocaleString()}
                        </span>
                      </div>
                      <p className="text-var-text whitespace-pre-wrap leading-relaxed pl-10">
                        {reply.message}
                      </p>
                    </div>
                  </div>
                ))
              )}
            </div>
          )}
        </div>
        
        {/* Action Panel - Status Update + Reply */}
        <div className="border-t border-var-border p-5 bg-var-surface-hover">
          <div className="space-y-4">
            {/* Status Update Section */}
            {canUpdateStatus && (
              <div className="flex items-center gap-4 flex-wrap p-3 bg-var-surface rounded-lg border border-var-border">
                <div className="flex items-center gap-2">
                  <Clock className="h-4 w-4 text-var-primary" />
                  <span className="text-sm font-medium text-var-text">Update Status:</span>
                </div>
                <select
                  value={selectedStatus}
                  onChange={(e) => handleStatusChange(e.target.value)}
                  className="px-3 py-1.5 text-sm bg-var-input border border-var-border rounded-lg focus:ring-2 focus:ring-var-primary focus:border-var-primary text-var-text cursor-pointer"
                >
                  <option value="open">Open</option>
                  <option value="in_progress">In Progress</option>
                  <option value="resolved">Resolved</option>
                  <option value="closed">Closed</option>
                </select>
                {isStatusChanged && (
                  <span className="text-xs text-var-warning flex items-center gap-1">
                    <span className="inline-block w-2 h-2 bg-var-warning rounded-full"></span>
                    Status changed (pending save)
                  </span>
                )}
              </div>
            )}
            
            {/* Reply Section */}
            {canReply && (
              <div>
                <label className="block text-sm font-medium text-var-text mb-2">
                  Add Reply
                </label>
                <textarea
                  value={newMessage}
                  onChange={(e) => setNewMessage(e.target.value)}
                  placeholder="Type your reply here... The customer will be notified via email."
                  rows={4}
                  className="w-full px-4 py-3 bg-var-input border border-var-border rounded-xl focus:ring-2 focus:ring-var-primary focus:border-var-primary resize-none text-var-text placeholder-var-input transition-colors"
                />
              </div>
            )}
            
            {/* Action Buttons */}
            <div className="flex justify-end gap-3 pt-2">
              <button
                type="button"
                onClick={onClose}
                className="px-5 py-2 border border-var-border rounded-xl text-var-text-secondary hover:bg-var-surface hover:text-var-text transition-all duration-200 font-medium"
              >
                Cancel
              </button>
              <button
                onClick={handleSubmit}
                disabled={isSubmitting || !canSubmit}
                className="inline-flex items-center px-5 py-2 bg-var-primary text-white rounded-xl hover:opacity-90 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed shadow-var-button font-medium"
              >
                {isSubmitting ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                    Saving...
                  </>
                ) : (
                  <>
                    <Save className="h-4 w-4 mr-2" />
                    Save Changes
                  </>
                )}
              </button>
            </div>
            
            {/* Help Text */}
            {canSubmit && (
              <p className="text-xs text-var-text-muted text-center pt-2 border-t border-var-border">
                <span className="inline-block w-2 h-2 bg-var-info rounded-full mr-1"></span>
                {isStatusChanged && newMessage.trim() && "Status change + reply will be saved together"}
                {isStatusChanged && !newMessage.trim() && "Only status change will be saved"}
                {!isStatusChanged && newMessage.trim() && "Only reply will be sent"}
              </p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}