import { useState } from "react";
import styles from "../../../ChatbotSettings.module.css";
import { FiMoreVertical, FiLink, FiZap, FiEdit2, FiChevronLeft, FiMonitor, FiSearch, FiEye, FiTrash2, FiPlus } from "react-icons/fi";
import { useGetAssistant, useUpdateShoppingSkills } from "app/utils/api";
import { useToast } from "app/components/providers/use-toast";

export default function ProductRecommendationsDetail() {
    const { data: assistantData, isLoading } = useGetAssistant();
    const updateShoppingSkills = useUpdateShoppingSkills();
    const { showSuccess, showError } = useToast();

    const [editingRec, setEditingRec] = useState<any>(null); // State to handle the detailed edit view

    const assistant = assistantData?.data || {};
    const shopping = assistant.assistant_skills?.shopping_skills || assistant.shopping_skills || {};
    const systemRecs = shopping.product_recommendations?.system_recommendations || [
        { id: "rec_01", title: "Best sellers", description: "Product recommendations for \"What are your best sellers?\"", product_count: 0, last_modified: "02/04/2026 14:51", status: "active" },
        { id: "rec_02", title: "New arrivals", description: "Product recommendations for \"Any new items?\"", product_count: 0, last_modified: "02/04/2026 14:51", status: "active" },
    ];

    const customRecs = [
        { title: "Special occasions", badge: "New", desc: "Recommend products perfect for gifts and special events", products: "--", updated: "--", status: "--" },
        { title: "Sale promotion", badge: "New", desc: "Highlight discounted items and promotional offers", products: "--", updated: "--", status: "--" },
    ];

    const handleToggleStatus = async (recId: string, currentStatus: string) => {
        try {
            const newStatus = currentStatus === "active" ? "inactive" : "active";
            const updatedSystemRecs = systemRecs.map((r: any) => 
                r.id === recId ? { ...r, status: newStatus } : r
            );
            
            await updateShoppingSkills.mutateAsync({
                ...shopping,
                product_recommendations: {
                    ...(shopping.product_recommendations || {}),
                    system_recommendations: updatedSystemRecs
                }
            });
            showSuccess("Status updated!");
        } catch (error) {
            showError("Failed to update status.");
        }
    };

    if (isLoading) return <div style={{ padding: '20px', textAlign: 'center' }}>Loading...</div>;

    // Detailed Edit View (Image 2)
    if (editingRec) {
        return (
            <ProductRecommendationEdit 
                recommendation={editingRec} 
                onBack={() => setEditingRec(null)} 
            />
        );
    }

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
            {/* Page Header (Image 1) */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <FiChevronLeft 
                        style={{ cursor: 'pointer', fontSize: '20px' }} 
                        onClick={() => {/* This should go back to Skills Tab, maybe controlled by parent */}}
                    />
                    <div>
                        <h2 style={{ fontSize: '20px', fontWeight: 700, margin: 0 }}>Product recommendations</h2>
                        <p style={{ fontSize: '13px', color: '#6b7280', margin: 0 }}>Suggest the right products for each customer</p>
                    </div>
                </div>
                <button className={styles.secondaryBtn} style={{ background: '#f3f4f6', display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <FiMonitor /> Test AI
                </button>
            </div>

            {/* System Recommendations Card */}
            <div className={styles.instructionCard}>
                <h3 className={styles.instructionTitle}>System recommendations</h3>
                <p className={styles.instructionDesc}>Pre-configured recommendations that automatically respond to common customer intents.</p>

                <div className={styles.tableWrapper}>
                    <table className={styles.tableContainer}>
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Products</th>
                                <th>Last modified</th>
                                <th>Status</th>
                                <th style={{ width: '80px' }}>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {systemRecs.map((rec: any, i: number) => (
                                <tr key={i}>
                                    <td>
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                            <span style={{ fontWeight: 700 }}>{rec.title}</span>
                                            <span style={{ fontSize: '11px', color: '#6b7280' }}>{rec.description}</span>
                                        </div>
                                    </td>
                                    <td>{rec.product_count || 0}</td>
                                    <td>{rec.last_modified}</td>
                                    <td>
                                        <label className={styles.switch}>
                                            <input 
                                                type="checkbox" 
                                                checked={rec.status === "active"} 
                                                onChange={() => handleToggleStatus(rec.id, rec.status)}
                                            />
                                            <span className={styles.slider}></span>
                                        </label>
                                    </td>
                                    <td>
                                        <div style={{ display: 'flex', gap: '12px' }}>
                                            <FiEdit2 
                                                style={{ cursor: 'pointer', color: '#6b7280' }} 
                                                onClick={() => setEditingRec(rec)}
                                            />
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
                <div className={styles.paginationRow}>
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                         <button className={styles.iconBtn} disabled><FiChevronLeft /></button>
                         <span className={styles.toggleDesc}>Page 1/1</span>
                         <button className={styles.iconBtn} disabled><FiChevronLeft style={{ transform: 'rotate(180deg)' }} /></button>
                    </div>
                    <div className={styles.itemsPerPage}>
                        Items per page <select className={styles.selectSm}><option>10</option></select>
                    </div>
                </div>
            </div>

            {/* Custom Recommendations Card */}
            <div className={styles.instructionCard}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '4px' }}>
                    <h3 className={styles.instructionTitle} style={{ margin: 0 }}>Custom recommendations</h3>
                    <span className={styles.badgeBlue}><FiZap className={styles.upgradeIcon} /> Upgrade</span>
                </div>
                <p className={styles.instructionDesc}>Create custom recommendation rules for specific use cases like gifts, occasions, or seasonal campaigns.</p>

                <div className={styles.tableWrapper}>
                    <table className={styles.tableContainer} style={{ opacity: 0.7 }}>
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Products</th>
                                <th>Last modified</th>
                                <th>Status</th>
                                <th style={{ width: '80px' }}>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {customRecs.map((rec, i) => (
                                <tr key={i}>
                                    <td>
                                        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                <span style={{ fontWeight: 700 }}>{rec.title}</span>
                                                <span className={styles.badgeYellow}>{rec.badge}</span>
                                            </div>
                                            <span style={{ fontSize: '11px', color: '#6b7280' }}>{rec.desc}</span>
                                        </div>
                                    </td>
                                    <td>{rec.products}</td>
                                    <td>{rec.updated}</td>
                                    <td>--</td>
                                    <td>
                                        <FiEdit2 style={{ color: '#d1d5db' }} />
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
                <div className={styles.paginationRow}>
                     <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                         <button className={styles.iconBtn} disabled><FiChevronLeft /></button>
                         <span className={styles.toggleDesc}>Page 1/1</span>
                         <button className={styles.iconBtn} disabled><FiChevronLeft style={{ transform: 'rotate(180deg)' }} /></button>
                    </div>
                    <div className={styles.itemsPerPage}>
                        Items per page <select className={styles.selectSm}><option>10</option></select>
                    </div>
                </div>
            </div>
        </div>
    );
}

function ProductRecommendationEdit({ recommendation, onBack }: { recommendation: any, onBack: () => void }) {
    const { data: assistantData } = useGetAssistant();
    const updateShoppingSkills = useUpdateShoppingSkills();
    const { showSuccess, showError } = useToast();

    const [enabled, setEnabled] = useState(recommendation.status === "active");
    const [smartSync, setSmartSync] = useState(true);
    const [searchQuery, setSearchQuery] = useState("");
    
    // Modal states
    const [viewProduct, setViewProduct] = useState<any>(null);
    const [showBrowse, setShowBrowse] = useState(false);

    // Simulated product data as per Image 2
    const products = [
        { id: "1", name: "Gift Card", collections: "", tags: ["best_selling", "newest"], image: "https://via.placeholder.com/40" },
        { id: "2", name: "Selling Plans Ski Wax", collections: "", tags: ["Accessory", "Sport", "Winter", "+2"], image: "https://via.placeholder.com/40" },
        { id: "3", name: "The 3p Fulfilled Snowboard", collections: "", tags: ["Accessory", "Sport", "Winter", "+2"], image: "https://via.placeholder.com/40" },
    ];

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                    <FiChevronLeft style={{ cursor: 'pointer', fontSize: '20px' }} onClick={onBack} />
                    <div>
                        <h2 style={{ fontSize: '20px', fontWeight: 700, margin: 0 }}>{recommendation.title}</h2>
                        <p style={{ fontSize: '13px', color: '#6b7280', margin: 0 }}>{recommendation.description}</p>
                    </div>
                </div>
                <div style={{ display: 'flex', gap: '12px' }}>
                     <button className={styles.cancelButton} style={{ background: '#f3f4f6', border: 'none' }}>Restore to default</button>
                     <button 
                        className={styles.saveButton} 
                        style={{ background: '#111', color: '#fff', borderRadius: '8px' }}
                        onClick={() => setShowBrowse(true)}
                    >
                        Add products
                    </button>
                </div>
            </div>

            <div className={styles.instructionCard} style={{ padding: '16px' }}>
                <div className={styles.toggleRow} style={{ borderBottom: '1px solid #f3f4f6', paddingBottom: '12px' }}>
                    <span className={styles.selectionTitle} style={{ fontSize: '14px' }}>Enable recommendation</span>
                    <label className={styles.switch}>
                        <input type="checkbox" checked={enabled} onChange={e => setEnabled(e.target.checked)} />
                        <span className={styles.slider}></span>
                    </label>
                </div>
                <div className={styles.toggleRow} style={{ paddingTop: '12px' }}>
                    <span className={styles.selectionTitle} style={{ fontSize: '14px' }}>Activate smart syncing</span>
                    <label className={styles.switch}>
                        <input type="checkbox" checked={smartSync} onChange={e => setSmartSync(e.target.checked)} />
                        <span className={styles.slider}></span>
                    </label>
                </div>
            </div>

            <div className={styles.instructionCard}>
                 <div style={{ display: 'flex', gap: '12px', marginBottom: '16px' }}>
                     <div className={styles.searchContainer} style={{ flex: 1, position: 'relative' }}>
                         <FiSearch style={{ position: 'absolute', left: '12px', top: '12px', color: '#9ca3af' }} />
                         <input 
                            type="text" 
                            className={styles.inputField} 
                            style={{ paddingLeft: '40px', width: '100%', borderRadius: '8px', border: '1px solid #e5e7eb' }} 
                            placeholder="Search products by name"
                            value={searchQuery}
                            onChange={e => setSearchQuery(e.target.value)}
                         />
                     </div>
                     <select className={styles.selectSm} style={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}><option>Vendors</option></select>
                     <select className={styles.selectSm} style={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}><option>Tag</option></select>
                     <select className={styles.selectSm} style={{ borderRadius: '8px', border: '1px solid #e5e7eb' }}><option>Collections</option></select>
                 </div>

                 <div className={styles.tableWrapper}>
                    <table className={styles.tableContainer}>
                        <thead>
                            <tr>
                                <th style={{ width: '40px' }}><input type="checkbox" /></th>
                                <th>Product</th>
                                <th>Collections</th>
                                <th>Tags</th>
                                <th style={{ width: '80px' }}>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {products.map((p, i) => (
                                <tr key={i}>
                                    <td><input type="checkbox" /></td>
                                    <td>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                            <img src={p.image} style={{ width: '40px', height: '40px', borderRadius: '4px' }} alt="" />
                                            <span style={{ fontWeight: 600 }}>{p.name}</span>
                                        </div>
                                    </td>
                                    <td>{p.collections || "--"}</td>
                                    <td>
                                        <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
                                            {p.tags.map((t, ti) => (
                                                <span key={ti} style={{ background: '#f3f4f6', padding: '2px 8px', borderRadius: '12px', fontSize: '11px', color: '#4b5563' }}>{t}</span>
                                            ))}
                                        </div>
                                    </td>
                                    <td>
                                        <div style={{ display: 'flex', gap: '12px', color: '#6b7280' }}>
                                            <FiEye style={{ cursor: 'pointer' }} onClick={() => setViewProduct(p)} />
                                            <FiTrash2 style={{ cursor: 'pointer', color: '#ef4444' }} />
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                 </div>
                 <div className={styles.paginationRow}>
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                         <button className={styles.iconBtn} style={{ background: '#f3f4f6', color: '#9ca3af' }} disabled><FiChevronLeft /></button>
                         <span className={styles.toggleDesc} style={{ fontSize: '13px' }}>Page 1/2</span>
                         <button className={styles.iconBtn} style={{ background: '#f3f4f6' }}><FiChevronLeft style={{ transform: 'rotate(180deg)' }} /></button>
                    </div>
                    <div className={styles.itemsPerPage} style={{ fontSize: '13px' }}>
                        Items per page <select className={styles.selectSm} style={{ border: '1px solid #e5e7eb' }}><option>10</option></select>
                    </div>
                </div>
            </div>

            {/* View Product Modal (Image 3) */}
            {viewProduct && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent} style={{ maxWidth: '600px', borderRadius: '16px' }}>
                        <div className={styles.modalHeader}>
                            <h3 className={styles.modalTitle}>View product</h3>
                            <button className={styles.closeButton} onClick={() => setViewProduct(null)}>&times;</button>
                        </div>
                        <div className={styles.modalBody} style={{ padding: '0 0 20px 0' }}>
                             <div className={styles.productDetailGrid}>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>ID</span>
                                     <span className={styles.purpleLink} style={{ textDecoration: 'none' }}>8435870138468</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Status</span>
                                     <span style={{ fontWeight: 500 }}>ACTIVE</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Title</span>
                                     <span style={{ fontWeight: 500 }}>{viewProduct.name}</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>URL</span>
                                     <span className={styles.purpleLink} style={{ textDecoration: 'none' }}>https://pritam-dev.myshopify.com/products/gift-card</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Collections</span>
                                     <span>--</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Description</span>
                                     <span>This is a gift card for the store</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Tags</span>
                                     <div style={{ display: 'flex', gap: '8px' }}>
                                         <span className={styles.badgeGray} style={{ background: '#f3f4f6', padding: '4px 8px', borderRadius: '8px', fontSize: '12px' }}>best_selling</span> 
                                         <span className={styles.badgeGray} style={{ background: '#f3f4f6', padding: '4px 8px', borderRadius: '8px', fontSize: '12px' }}>newest</span>
                                     </div>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Options</span>
                                     <span>Denominations: $10, $25, $50, $100</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0', borderBottom: '1px solid #f9fafb' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Prices</span>
                                     <span>10, 10.00: ($10), 25.00: ($25), 50.00: ($50), 100, 100.00: ($100)</span>
                                 </div>
                                 <div className={styles.detailRow} style={{ padding: '12px 0' }}>
                                     <span style={{ color: '#6b7280', fontWeight: 500 }}>Vendor</span>
                                     <span>Snowboard Vendor</span>
                                 </div>
                             </div>
                        </div>
                        <div className={styles.modalFooter} style={{ borderTop: 'none', padding: '0 0 10px 0', display: 'flex', justifyContent: 'flex-end' }}>
                             <button className={styles.cancelButton} style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px', padding: '10px 30px' }} onClick={() => setViewProduct(null)}>Close</button>
                        </div>
                    </div>
                </div>
            )}

            {/* Browse Products Modal (Image 4) */}
            {showBrowse && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent} style={{ maxWidth: '700px', borderRadius: '16px' }}>
                        <div className={styles.modalHeader}>
                            <h3 className={styles.modalTitle}>Browse products</h3>
                            <button className={styles.closeButton} onClick={() => setShowBrowse(false)}>&times;</button>
                        </div>
                        <div className={styles.modalBody}>
                            <div className={styles.searchContainer} style={{ position: 'relative', marginBottom: '12px' }}>
                                <FiSearch style={{ position: 'absolute', left: '12px', top: '12px', color: '#9ca3af' }} />
                                <input type="text" className={styles.inputField} style={{ paddingLeft: '40px', width: '100%', borderRadius: '8px', border: '1px solid #e5e7eb' }} placeholder="Search products" />
                            </div>
                            <button className={styles.cancelButton} style={{ marginBottom: '16px', background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px', padding: '8px 16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
                                 <FiPlus /> Add filter
                            </button>
                            
                            <div className={styles.tableWrapper} style={{ maxHeight: '400px', overflowY: 'auto' }}>
                                <table className={styles.tableContainer}>
                                    <tbody>
                                        {[
                                            { name: "Gift Card", desc: "0 in stock for 4 variants" },
                                            { name: "Selling Plans Ski Wax", desc: "30 in stock for 3 variants" },
                                            { name: "The 3p Fulfilled Snowboard", desc: "20 in stock" },
                                            { name: "The Collection Snowboard: Hydrogen", desc: "50 in stock" }
                                        ].map((p, i) => (
                                            <tr key={i} style={{ cursor: 'pointer' }}>
                                                <td style={{ width: '40px' }}><input type="checkbox" style={{ width: '18px', height: '18px' }} /></td>
                                                <td>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                        <img src="https://via.placeholder.com/40" style={{ width: '44px', height: '44px', borderRadius: '4px', border: '1px solid #f3f4f6' }} alt="" />
                                                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                                                            <span style={{ fontWeight: 600, fontSize: '14px' }}>{p.name}</span>
                                                            <span style={{ fontSize: '11px', color: '#6b7280' }}>{p.desc}</span>
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div className={styles.modalFooter} style={{ borderTop: '1px solid #f3f4f6', paddingTop: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                             <span style={{ fontSize: '13px', color: '#6b7280', fontWeight: 500 }}>0 products selected</span>
                             <div style={{ display: 'flex', gap: '12px' }}>
                                <button className={styles.cancelButton} style={{ background: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px', padding: '10px 24px' }} onClick={() => setShowBrowse(false)}>Cancel</button>
                                <button className={styles.saveButton} style={{ background: '#111', color: '#fff', borderRadius: '8px', padding: '10px 32px' }}>Add</button>
                             </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

