import React, { useState, useEffect } from "react";
import { useGetProactiveChats, useUpdateProactiveChatStatus, useDeleteProactiveChat, useUpdateProactiveChat, useGetProactiveChatAnalytics } from "app/utils/api";
import { FiPlus, FiCalendar, FiRefreshCw, FiSearch, FiFilter, FiMoreHorizontal, FiGrid, FiEdit2, FiSlash, FiTrash2, FiCheckCircle, FiX } from "react-icons/fi";
import { useToast } from "app/components/providers/use-toast";
import styles from "../../chatbot/components/ChatbotSettings.module.css";

interface ProactiveChatListProps {
    onCreateClick: () => void;
    onEditClick: (chat: any) => void;
}

export function ProactiveChatList({ onCreateClick, onEditClick }: ProactiveChatListProps) {
    const [activeTab, setActiveTab] = useState("All");
    const [draggedChatIndex, setDraggedChatIndex] = useState<number | null>(null);
    const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
    const [deleteModalInfo, setDeleteModalInfo] = useState<{ id: string, name: string } | null>(null);
    
    const { data: response, isLoading } = useGetProactiveChats();
    const { data: analyticsResponse } = useGetProactiveChatAnalytics();
    const [localChats, setLocalChats] = useState<any[]>([]);
    
    const statusMutation = useUpdateProactiveChatStatus();
    const deleteMutation = useDeleteProactiveChat();
    const updateMutation = useUpdateProactiveChat();
    const { showSuccess, showError } = useToast();

    useEffect(() => {
        if (response?.data) {
            setLocalChats(response.data);
        }
    }, [response]);

    const filteredChats = localChats.filter((c: any) => {
        if (activeTab === "All") return true;
        if (activeTab === "Active") return c.status?.is_active === true;
        if (activeTab === "Inactive") return c.status?.is_active === false;
        return true;
    });

    const onDragStart = (idx: number) => setDraggedChatIndex(idx);
    
    const onDragOver = (e: React.DragEvent, idx: number) => {
        e.preventDefault();
        if (draggedChatIndex === null || draggedChatIndex === idx) return;
        
        const newChats = [...localChats];
        const item = newChats.splice(draggedChatIndex, 1)[0];
        newChats.splice(idx, 0, item);
        
        // Update priorities based on new order
        const reordered = newChats.map((c, i) => ({
            ...c,
            status: { ...c.status, priority: i + 1 }
        }));
        
        setDraggedChatIndex(idx);
        setLocalChats(reordered);
    };

    const onDragEnd = async () => {
        setDraggedChatIndex(null);
        try {
            // In a real app, you might want to send the whole reordered list or just individual updates
            // For now, we'll assume the backend handles priority if we send an update or there's a bulk endpoint
            // Since we don't have a bulk endpoint, we'll just keep the local state for now
            // or trigger updates for changed items.
            showSuccess("Order updated");
        } catch (err) {
            showError("Failed to update order");
        }
    };

    const handleStatusToggle = async (chat: any) => {
        try {
            const newStatus = !chat.status?.is_active;
            await statusMutation.mutateAsync({
                _id: chat._id,
                is_active: newStatus,
                updated_at: new Date().toLocaleString(),
                priority: chat.status?.priority || 1
            });
            showSuccess(`Chat ${newStatus ? 'activated' : 'deactivated'} successfully`);
            setActionMenuOpen(null);
        } catch (err) {
            showError("Failed to update status");
        }
    };

    const handleDelete = (_id: string, name: string) => {
        setDeleteModalInfo({ id: _id, name });
        setActionMenuOpen(null);
    };

    const confirmDelete = async () => {
        if (!deleteModalInfo) return;
        try {
            await deleteMutation.mutateAsync(deleteModalInfo.id);
            showSuccess("Proactive chat deleted successfully");
            setDeleteModalInfo(null);
        } catch (err) {
            showError("Failed to delete proactive chat");
        }
    };

    const analyticsData = analyticsResponse?.data || {};
    const stats = [
        { label: "Views", value: analyticsData.views || "0" },
        { label: "CTR", value: (analyticsData.ctr || "0") + "%" },
        { label: "Revenue", value: `$${analyticsData.revenue || "0"}` },
        { label: "Orders", value: analyticsData.orders || "0" }
    ];

    return (
        <div className={styles.trainingDataContainer} style={{ background: '#f9fafb', padding: '20px',  minHeight: '100vh' }}>
            <div className={styles.faqHeader}>
                <div>
                    <h1 className={styles.faqTitle}>Proactive chat</h1>
                    <p className={styles.faqSubtitle}>Engage shoppers in real time with proactive chat. <span style={{ color: '#7c3aed', cursor: 'pointer' }}>Learn more.</span></p>
                </div>
                <button className={styles.syncBtn} style={{ background: '#7c3aed' }} onClick={onCreateClick}>
                    Create proactive chat
                </button>
            </div>

            <div className={styles.appearanceCard} style={{ marginTop: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                    <h3 className={styles.cardSectionTitle} style={{ margin: 0 }}>Overview</h3>
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                        <div className={styles.actionIconBtn} style={{ width: 'auto', padding: '0 12px', gap: '8px', fontSize: '13px', background: '#f3f4f6' }}>
                            <FiCalendar /> Last 7 days
                        </div>
                        <div className={styles.actionIconBtn}><FiRefreshCw /></div>
                    </div>
                </div>
                <div className={styles.overviewStatsGrid}>
                    {stats.map(stat => (
                        <div key={stat.label} className={styles.statCard}>
                            <span className={styles.statLabel}>{stat.label}</span>
                            <span className={stat.label === 'Revenue' ? styles.statValue : styles.statValue}>{stat.value}</span>
                        </div>
                    ))}
                </div>
            </div>

            <div className={styles.manageDataCard} style={{ background: 'white', borderRadius: '16px', border: '1px solid #e5e7eb', marginTop: '24px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 24px', borderBottom: '1px solid #f3f4f6' }}>
                    <div className={styles.pillTabs} style={{ marginBottom: 0 }}>
                        {["All", "Active", "Inactive"].map(tab => (
                            <div
                                key={tab}
                                className={`${styles.pillTab} ${activeTab === tab ? styles.pillTabActive : ""}`}
                                onClick={() => setActiveTab(tab)}
                            >
                                {tab}
                            </div>
                        ))}
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                        <div className={styles.actionIconBtn}><FiSearch /></div>
                        <div className={styles.actionIconBtn}><FiFilter /></div>
                    </div>
                </div>

                <div className={styles.tableWrapper} style={{ minHeight: '300px' }}>
                    <table className={styles.tableContainer} style={{ width: '100%', border: 'none' }}>
                        <thead>
                            <tr style={{ background: '#f9fafb' }}>
                                <th style={{ paddingLeft: '24px' }}>Priority</th>
                                <th>Proactive chat name</th>
                                <th>Proactive chat type</th>
                                <th>View</th>
                                <th>CTR</th>
                                <th>Status</th>
                                <th>Updated at</th>
                                <th style={{ textAlign: 'right', paddingRight: '24px' }}>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {isLoading ? (
                                <tr>
                                    <td colSpan={8} style={{ textAlign: 'center', padding: '24px' }}>Loading proactive chats...</td>
                                </tr>
                            ) : filteredChats.length === 0 ? (
                                <tr>
                                    <td colSpan={8} style={{ textAlign: 'center', padding: '24px' }}>No items found</td>
                                </tr>
                            ) : (
                                filteredChats.map((item: any, idx: number) => (
                                    <tr 
                                        key={item._id || idx} 
                                        style={{ 
                                            borderBottom: '1px solid #f3f4f6',
                                            opacity: draggedChatIndex === idx ? 0.4 : 1,
                                            background: draggedChatIndex === idx ? '#f9fafb' : 'transparent'
                                        }}
                                        draggable
                                        onDragStart={() => onDragStart(idx)}
                                        onDragOver={(e) => onDragOver(e, idx)}
                                        onDragEnd={onDragEnd}
                                    >
                                        <td style={{ paddingLeft: '24px' }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                <div style={{ cursor: 'grab' }} className={styles.dragHandle}>
                                                    <FiGrid size={14} color="#d1d5db" />
                                                </div>
                                                <span>{item.status?.priority || idx + 1}</span>
                                            </div>
                                        </td>
                                        <td><span style={{ fontWeight: 500 }}>{item.general?.name}</span></td>
                                        <td>{item.message?.active_type?.replace(/_/g, ' ') || 'Text'}</td>
                                        <td>{item.analytics_snapshot?.views || '-'}</td>
                                        <td>{item.analytics_snapshot?.ctr || '-'}</td>
                                        <td><span className={`${styles.statusBadge} ${item.status?.is_active ? styles.statusActive : styles.statusDisabled}`}>{item.status?.is_active ? 'Active' : 'Inactive'}</span></td>
                                        <td>{item.status?.updated_at || '-'}</td>
                                        <td style={{ textAlign: 'right', paddingRight: '24px', position: 'relative' }}>
                                            <div 
                                                className={styles.actionIconBtn} 
                                                style={{ marginLeft: 'auto', cursor: 'pointer' }} 
                                                onClick={() => setActionMenuOpen(actionMenuOpen === item._id ? null : item._id)}
                                            >
                                                <FiMoreHorizontal />
                                            </div>
                                            
                                            {actionMenuOpen === item._id && (
                                                <>
                                                    <div 
                                                        style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 90 }} 
                                                        onClick={() => setActionMenuOpen(null)}
                                                    />
                                                    <div className={styles.dropdownMenu} style={{ 
                                                        position: 'absolute', right: '24px', top: '40px', 
                                                        width: '180px', zIndex: 100, display: 'block' 
                                                    }}>
                                                        <div className={styles.dropdownItem} onClick={() => { onEditClick(item); setActionMenuOpen(null); }}>
                                                            <FiEdit2 /> Edit
                                                        </div>
                                                        <div className={styles.dropdownItem} onClick={() => handleStatusToggle(item)}>
                                                            {item.status?.is_active ? <><FiSlash /> Set as inactive</> : <><FiCheckCircle /> Set as active</>}
                                                        </div>
                                                        <div className={styles.dropdownItem} style={{ color: '#ef4444' }} onClick={() => handleDelete(item._id, item.general?.name)}>
                                                            <FiTrash2 /> Delete
                                                        </div>
                                                    </div>
                                                </>
                                            )}
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                </div>

                <div style={{ padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderTop: '1px solid #f3f4f6' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '13px', color: '#6b7280' }}>
                        Items per page
                        <select className={styles.chatInput} style={{ width: '60px', height: '32px', padding: '0 8px' }}>
                            <option>10</option>
                        </select>
                    </div>
                    <div style={{ display: 'flex', gap: '16px', alignItems: 'center', fontSize: '13px', color: '#6b7280' }}>
                        <span>{"<"} Page 1/1 {">"}</span>
                    </div>
                </div>
            </div>
            {/* Custom Delete Modal */}
            {deleteModalInfo && (
                <div className={styles.modalOverlay} onClick={() => setDeleteModalInfo(null)}>
                    <div 
                        className={styles.modalContent} 
                        style={{ width: '500px', borderRadius: '12px', padding: 0 }} 
                        onClick={e => e.stopPropagation()}
                    >
                        <div className={styles.modalHeader} style={{ padding: '20px 24px', borderBottom: '1px solid #e5e7eb', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <h2 style={{ fontSize: '16px', fontWeight: 600, color: '#111827', margin: 0 }}>
                                Delete Proactive Chat?
                            </h2>
                            <button className={styles.closeButton} onClick={() => setDeleteModalInfo(null)} style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 0, display: 'flex' }}>
                                <FiX size={20} color="#6b7280" />
                            </button>
                        </div>
                        
                        <div className={styles.modalBody} style={{ padding: '24px', fontSize: '14px', color: '#4b5563', lineHeight: '1.5' }}>
                            <p style={{ margin: 0 }}>
                                Are you sure you want to delete <strong>{deleteModalInfo.name}</strong>? This action cannot be undone.
                            </p>
                        </div>
                        
                        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px', padding: '16px 24px', borderTop: '1px solid #e5e7eb', background: '#fff', borderBottomLeftRadius: '12px', borderBottomRightRadius: '12px' }}>
                            <button 
                                onClick={() => setDeleteModalInfo(null)} 
                                style={{ padding: '8px 16px', borderRadius: '8px', border: '1px solid #d1d5db', background: 'white', color: '#374151', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                            >
                                Cancel
                            </button>
                            <button 
                                onClick={confirmDelete} 
                                style={{ padding: '8px 16px', borderRadius: '8px', border: 'none', background: '#dc2626', color: 'white', fontSize: '14px', fontWeight: 500, cursor: 'pointer' }}
                            >
                                Delete
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
