const ITSupportView = ({ showCreateForm, onShowCreateForm, initialDescription, initialDraft = null, initialAttachments = [], fromAIChat, onBackToChat }) => {
    const { useState, useEffect } = React;
    const [tickets, setTickets] = useState([]);
    const [comments, setComments] = useState({});
    const [selectedTicket, setSelectedTicket] = useState(null);
    const [replyText, setReplyText] = useState('');
    const [searchText, setSearchText] = useState('');
    const [statusFilter, setStatusFilter] = useState('All Statuses');
    const [priorityFilter, setPriorityFilter] = useState('All Priorities');
    const [createdFilter, setCreatedFilter] = useState('Created (All Time)');
    const [updatedFilter, setUpdatedFilter] = useState('Updated (All Time)');
    const [editingCommentId, setEditingCommentId] = useState(null);
    const [editCommentText, setEditCommentText] = useState('');

    useEffect(() => {
        if (tickets.length > 0 && !selectedTicket && !showCreateForm) {
            setSelectedTicket(tickets[0]);
        }
    }, [showCreateForm, tickets]);

    const filterByTime = (dateString, filter) => {
        const date = new Date(dateString);
        const now = new Date();
        const diffMinutes = (now - date) / 60000;

        if (filter.includes('Last Hour')) return diffMinutes <= 60;
        if (filter.includes('Last 24 Hours')) return diffMinutes <= 1440;
        if (filter.includes('Last 7 Days')) return diffMinutes <= 10080;
        if (filter.includes('Last 30 Days')) return diffMinutes <= 43200;
        return true;
    };

    const filteredTickets = tickets.filter(ticket => {
        const matchesStatus = statusFilter === 'All Statuses' || ticket.Status === statusFilter;
        const matchesPriority = priorityFilter === 'All Priorities' || ticket.Priority === priorityFilter;
        const matchesCreated = filterByTime(ticket.IssueDate, createdFilter);
        const matchesUpdated = filterByTime(ticket.LastUpdated, updatedFilter);
        const matchesSearch = searchText === '' ||
            ticket.Subject.toLowerCase().includes(searchText.toLowerCase()) ||
            ticket.IssueID.toString().includes(searchText) ||
            ticket.Category.toLowerCase().includes(searchText.toLowerCase());

        return matchesStatus && matchesPriority && matchesCreated && matchesUpdated && matchesSearch;
    });

    const handleSendReply = () => {
        if (!replyText.trim() || !selectedTicket) return;

        const newComment = {
            CommentID: Math.floor(Math.random() * 90000) + 10000,
            UserName: "Hotel Rep",
            CommentDate: new Date().toISOString(),
            Body: replyText,
            IsSystem: false
        };

        setComments(prev => ({
            ...prev,
            [selectedTicket.IssueID]: [...(prev[selectedTicket.IssueID] || []), newComment]
        }));

        setTickets(prev => prev.map(t =>
            t.IssueID === selectedTicket.IssueID
                ? { ...t, LastUpdated: new Date().toISOString() }
                : t
        ));

        setReplyText('');
    };

    const handleEditComment = (commentId, currentBody) => {
        setEditingCommentId(commentId);
        setEditCommentText(currentBody);
    };

    const handleSaveEdit = (commentId) => {
        if (!editCommentText.trim() || !selectedTicket) return;

        const originalComment = comments[selectedTicket.IssueID].find(c => c.CommentID === commentId);
        const textChanged = originalComment && editCommentText.trim() !== originalComment.Body.trim();

        setComments(prev => ({
            ...prev,
            [selectedTicket.IssueID]: prev[selectedTicket.IssueID].map(c =>
                c.CommentID === commentId
                    ? {
                        ...c,
                        Body: editCommentText,
                        CommentDate: textChanged ? new Date().toISOString() : c.CommentDate,
                        Edited: textChanged ? true : (c.Edited || false)
                    }
                    : c
            )
        }));

        setEditingCommentId(null);
        setEditCommentText('');
    };

    const handleCancelEdit = () => {
        setEditingCommentId(null);
        setEditCommentText('');
    };

    const handleTicketSubmit = (newTicket) => {
        setTickets(prev => [newTicket, ...prev]);
        if (!comments[newTicket.IssueID]) {
            setComments(prev => ({ ...prev, [newTicket.IssueID]: [] }));
        }
        setSelectedTicket(newTicket);

        // If ticket was created from AI chat, clear chat for new conversation
        if (fromAIChat && onBackToChat) {
            onBackToChat(true); // Pass true to indicate successful submission
        }
    };

    if (showCreateForm) {
        return <CreateTicketForm
            onBack={() => onShowCreateForm(false, '')}
            initialDescription={initialDescription}
            initialDraft={initialDraft}
            initialAttachments={initialAttachments}
            fromAIChat={fromAIChat}
            onBackToChat={onBackToChat}
            onSubmit={handleTicketSubmit}
        />;
    }

    return (
        <div className="flex h-full">
            <div className="w-[440px] border-r border-gray-200 bg-white flex flex-col">
                <div className="p-6 border-b border-gray-200">
                    <div className="flex items-center justify-between mb-4">
                        <h2 className="text-xl font-bold text-gray-800">Ticket History</h2>
                        <button
                            onClick={() => onShowCreateForm(true, '')}
                            className="bg-primary hover:bg-primary-hover text-white px-4 py-2 rounded-lg font-semibold transition-colors text-sm"
                        >
                            + Create Ticket
                        </button>
                    </div>

                    <div className="space-y-3">
                        <div className="grid grid-cols-2 gap-2">
                            <select
                                value={statusFilter}
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                            >
                                <option>All Statuses</option>
                                <option>In progress</option>
                                <option>Waiting</option>
                                <option>Closed</option>
                            </select>
                            <select
                                value={priorityFilter}
                                onChange={(e) => setPriorityFilter(e.target.value)}
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                            >
                                <option>All Priorities</option>
                                <option>Low</option>
                                <option>Normal</option>
                                <option>High</option>
                                <option>Critical</option>
                            </select>
                        </div>

                        <div className="grid grid-cols-2 gap-2">
                            <select
                                value={createdFilter}
                                onChange={(e) => setCreatedFilter(e.target.value)}
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                            >
                                <option>Created (All Time)</option>
                                <option>Created (Last Hour)</option>
                                <option>Created (Last 24 Hours)</option>
                                <option>Created (Last 7 Days)</option>
                                <option>Created (Last 30 Days)</option>
                            </select>
                            <select
                                value={updatedFilter}
                                onChange={(e) => setUpdatedFilter(e.target.value)}
                                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                            >
                                <option>Updated (All Time)</option>
                                <option>Updated (Last Hour)</option>
                                <option>Updated (Last 24 Hours)</option>
                                <option>Updated (Last 7 Days)</option>
                                <option>Updated (Last 30 Days)</option>
                            </select>
                        </div>

                        <input
                            type="text"
                            placeholder="Search (ticket #, subject, category)"
                            value={searchText}
                            onChange={(e) => setSearchText(e.target.value)}
                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"
                        />
                    </div>
                </div>

                <div className="flex-1 overflow-y-auto p-4 space-y-3 scrollbar-thin">
                    {filteredTickets.length === 0 ? (
                        <div className="text-center text-gray-500 py-8">No tickets match your filters</div>
                    ) : (
                        filteredTickets.map(ticket => (
                            <div
                                key={ticket.IssueID}
                                onClick={() => setSelectedTicket(ticket)}
                                className={`p-4 rounded-xl border-2 cursor-pointer transition-all ${selectedTicket?.IssueID === ticket.IssueID
                                        ? 'border-primary bg-primary/5'
                                        : 'border-gray-200 bg-white hover:border-gray-300'
                                    }`}
                            >
                                <div className="flex items-start gap-3">
                                    <div
                                        className="w-1.5 h-full rounded-full flex-shrink-0"
                                        style={{ backgroundColor: getStatusColor(ticket.Status, ticket.PriorityID) }}
                                    />
                                    <div className="flex-1 min-w-0">
                                        <div className="font-semibold text-gray-900 mb-1">
                                            #{ticket.IssueID} {ticket.Subject}
                                        </div>
                                        <div className="flex items-center gap-3 text-xs text-gray-600">
                                            <span className="flex items-center gap-1">
                                                <div
                                                    className="w-2 h-2 rounded-full"
                                                    style={{ backgroundColor: getStatusColor(ticket.Status, ticket.PriorityID) }}
                                                />
                                                {ticket.Status}
                                            </span>
                                            <span>{ticket.Priority}</span>
                                            <span>Updated {getRelativeTime(ticket.LastUpdated)}</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))
                    )}
                </div>
            </div>

            <div className="flex-1 bg-gray-50 overflow-y-auto scrollbar-thin">
                {selectedTicket ? (
                    <div className="p-8">
                        <div className="max-w-4xl mx-auto space-y-6">
                            <div className="bg-white rounded-xl border border-gray-200 p-6">
                                <div className="flex items-start justify-between mb-4">
                                    <h2 className="text-2xl font-bold text-gray-800 flex-1">
                                        {selectedTicket.Subject}
                                    </h2>
                                    <div className="flex items-center gap-3 ml-4">
                                        <span className="text-sm text-gray-500">#{selectedTicket.IssueID}</span>
                                        <div
                                            className="w-3 h-3 rounded-full"
                                            style={{ backgroundColor: getStatusColor(selectedTicket.Status, selectedTicket.PriorityID) }}
                                            title={selectedTicket.Status}
                                        />
                                    </div>
                                </div>

                                <div className="grid grid-cols-2 gap-4 text-sm mb-6">
                                    <div><span className="text-gray-600">Status: </span><span className="font-semibold">{selectedTicket.Status}</span></div>
                                    <div><span className="text-gray-600">Priority: </span><span className="font-semibold">{selectedTicket.Priority}</span></div>
                                    <div><span className="text-gray-600">Category: </span><span>{selectedTicket.Category}</span></div>
                                    <div><span className="text-gray-600">Assigned: </span><span>{selectedTicket.AssignedTo}</span></div>
                                    <div><span className="text-gray-600">Created: </span><span>{formatDate(selectedTicket.IssueDate)}</span></div>
                                    <div><span className="text-gray-600">Updated: </span><span>{formatDate(selectedTicket.LastUpdated)}</span></div>
                                </div>

                                {selectedTicket.Description && (
                                    <div className="pt-6 border-t border-gray-200">
                                        <h3 className="font-semibold text-gray-800 mb-3">Description</h3>
                                        <p className="text-gray-700 whitespace-pre-wrap break-words">{selectedTicket.Description}</p>
                                    </div>
                                )}
                            </div>

                            {comments[selectedTicket.IssueID] && comments[selectedTicket.IssueID].length > 0 && (
                                <div className="bg-white rounded-xl border border-gray-200 p-6">
                                    <h3 className="font-semibold text-gray-800 mb-4">Comments</h3>
                                    <div className="max-h-96 overflow-y-auto space-y-4 scrollbar-thin">
                                        {comments[selectedTicket.IssueID].map(comment => (
                                            <div
                                                key={comment.CommentID}
                                                className={`rounded-lg p-4 border-l-4 ${comment.UserName === "Hotel Rep"
                                                        ? 'bg-primary/5 border-l-primary border-y border-r border-primary/20'
                                                        : 'bg-gray-50/30 border-l-gray-400 border-y border-r border-gray-100'
                                                    }`}
                                            >
                                                <div className="flex items-center justify-between mb-2">
                                                    <span className={`font-semibold text-sm ${comment.UserName === "Hotel Rep" ? 'text-primary' : 'text-gray-700'
                                                        }`}>
                                                        {comment.UserName}
                                                    </span>
                                                    <div className="flex items-center gap-2">
                                                        <span className="text-xs text-gray-500">
                                                            {formatDate(comment.CommentDate)}
                                                            {comment.Edited && <span className="text-gray-400 ml-1">(edited)</span>}
                                                        </span>
                                                        {comment.UserName === "Hotel Rep" && editingCommentId !== comment.CommentID && (
                                                            <button
                                                                onClick={() => handleEditComment(comment.CommentID, comment.Body)}
                                                                className="text-xs text-primary hover:text-primary-hover font-semibold"
                                                            >
                                                                Edit
                                                            </button>
                                                        )}
                                                    </div>
                                                </div>
                                                {editingCommentId === comment.CommentID ? (
                                                    <div className="space-y-2">
                                                        <textarea
                                                            value={editCommentText}
                                                            onChange={(e) => setEditCommentText(e.target.value)}
                                                            rows="3"
                                                            className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm bg-white"
                                                        />
                                                        <div className="flex gap-2 justify-end">
                                                            <button
                                                                onClick={handleCancelEdit}
                                                                className="px-3 py-1 text-sm border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
                                                            >
                                                                Cancel
                                                            </button>
                                                            <button
                                                                onClick={() => handleSaveEdit(comment.CommentID)}
                                                                className="px-3 py-1 text-sm bg-primary text-white rounded-lg hover:bg-primary-hover"
                                                            >
                                                                Save
                                                            </button>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <p className="text-gray-800 break-words overflow-wrap-anywhere">{comment.Body}</p>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            <div className="bg-white rounded-xl border border-gray-200 p-6">
                                <h3 className="font-semibold text-gray-800 mb-3">Reply</h3>
                                {editingCommentId && (
                                    <div className="mb-3 text-sm text-amber-600 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                                        Reply disabled while editing a comment above
                                    </div>
                                )}
                                <textarea
                                    value={replyText}
                                    onChange={(e) => setReplyText(e.target.value)}
                                    rows="4"
                                    disabled={editingCommentId !== null}
                                    className="w-full border border-gray-300 rounded-lg px-4 py-2 mb-3 disabled:bg-gray-100 disabled:cursor-not-allowed"
                                    placeholder="Type your reply..."
                                />
                                <div className="flex gap-3 justify-end">
                                    <button
                                        onClick={() => setReplyText('')}
                                        disabled={editingCommentId !== null}
                                        className="px-6 py-2 border border-gray-300 rounded-lg font-semibold text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Clear
                                    </button>
                                    <button
                                        onClick={handleSendReply}
                                        disabled={!replyText.trim() || editingCommentId !== null}
                                        className="px-6 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Send Reply
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                ) : (
                    <div className="flex items-center justify-center h-full text-gray-500">
                        Select a ticket to view details
                    </div>
                )}
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.ITSupportView = ITSupportView;