import React, { useState, useEffect } from 'react';
import DataTable from '../../../Components/DataTable';
import Toast from '../Components/Toast';
import { 
    Package, 
    Plus, 
    AlertTriangle, 
    Search, 
    Filter, 
    Building, 
    Eye, 
    History, 
    ShoppingCart,
    ArrowUpRight,
    X,
    TrendingUp,
    MoreVertical,
    FileText,
    Settings,
    RefreshCw,
    BarChart3
} from 'lucide-react';

import AddProductModal from './AddProductModal';
import AdjustStockModal from './AdjustStockModal';
import ProductDetailsModal from './ProductDetailsModal';
import NewSaleModal from './NewSaleModal';

export default function InventoryIndex() {
    const [activeTab, setActiveTab] = useState('Stock Control');
    const [products, setProducts] = useState([]);
    const [movements, setMovements] = useState([]);
    const [branches, setBranches] = useState([]);
    const [categories, setCategories] = useState([]);
    const [loading, setLoading] = useState(true);
    const [movementsLoading, setMovementsLoading] = useState(false);
    const [toast, setToast] = useState(null);

    // Modals
    const [isAddModalOpen, setIsAddModalOpen] = useState(false);
    const [isAdjustModalOpen, setIsAdjustModalOpen] = useState(false);
    const [isDetailsModalOpen, setIsDetailsModalOpen] = useState(false);
    const [isSaleModalOpen, setIsSaleModalOpen] = useState(false);
    const [selectedProduct, setSelectedProduct] = useState(null);

    // Filters
    const [filterBranch, setFilterBranch] = useState(window.__APP_DATA__?.role === 'receptionist' ? window.__APP_DATA__?.user?.branch_id : '');
    const [filterStatus, setFilterStatus] = useState('');
    const [startDate, setStartDate] = useState('');
    const [endDate, setEndDate] = useState('');
    const [searchTerm, setSearchTerm] = useState('');

    const isReceptionist = window.__APP_DATA__?.role === 'receptionist';

    const fetchMasters = async () => {
        try {
            // Fetch branches
            const bRes = await fetch('/api/branches?status=Active');
            if (bRes.ok) {
                setBranches(await bRes.json());
            } else {
                console.error('Failed to fetch branches');
            }

            // Fetch categories from the Master API to ensure 1:1 match
            const cRes = await fetch('/api/masters/product');
            if (cRes.ok) {
                const cats = await cRes.json();
                // Filter for Active only if needed, or show all
                setCategories(cats.filter(c => c.status === 'Active'));
            } else {
                console.error('Failed to fetch product categories from master API');
            }
        } catch (error) {
            console.error('Master data fetch exception:', error);
        }
    };

    const fetchProducts = async () => {
        setLoading(true);
        try {
            const url = `/api/inventory/products?branch_id=${filterBranch}&status=${filterStatus}`;
            const res = await fetch(url);
            setProducts(await res.json());
        } finally {
            setLoading(false);
        }
    };

    // Fetch Sales moved to Global Reports

    const fetchMovements = async () => {
        setMovementsLoading(true);
        try {
            let url = `/api/inventory/movements?branch_id=${filterBranch}`;
            if (startDate) url += `&start_date=${startDate}`;
            if (endDate) url += `&end_date=${endDate}`;
            const res = await fetch(url);
            setMovements(await res.json());
        } catch (error) {
            console.error('Error fetching movements:', error);
        } finally {
            setMovementsLoading(false);
        }
    };

    useEffect(() => {
        fetchMasters();
    }, []);

    useEffect(() => {
        fetchProducts();
    }, [filterBranch, filterStatus, startDate, endDate]);

    useEffect(() => {
        if (activeTab === 'Reports & Alerts') {
            fetchMovements();
        }
    }, [activeTab, filterBranch, startDate, endDate]);

    const lowStockCount = products.filter(p => parseFloat(p.current_stock) <= parseFloat(p.reorder_level)).length;

    const stockColumns = [
        {
            header: 'Branch',
            render: (row) => <span className="text-gray-500 font-bold text-xs">{row.branch?.name}</span>
        },
        {
            header: 'Product Info',
            render: (row) => (
                <div className="flex flex-col">
                    <div className="flex items-center gap-2">
                        <span className="font-bold text-gray-900 text-sm">{row.name}</span>
                        <span className="text-[9px] bg-gray-50 text-gray-400 px-1.5 py-0.5 rounded border border-gray-100 font-black uppercase">{row.category?.name}</span>
                    </div>
                    <span className="text-[10px] text-gray-400 font-black tracking-widest uppercase">SKU-{row.sku}</span>
                </div>
            )
        },
        {
            header: 'Cost Price',
            render: (row) => <span className="text-gray-600 font-bold">{parseFloat(row.cost_price).toFixed(2)}</span>
        },
        {
            header: 'Selling Price',
            render: (row) => <span className="text-gray-600 font-bold">{parseFloat(row.selling_price).toFixed(2)}</span>
        },
        {
            header: 'Current Stock',
            render: (row) => <span className="font-black text-[#111827]">{row.current_stock}</span>
        },
        {
            header: 'Reorder Level',
            render: (row) => <span className="text-gray-400 font-bold">{row.reorder_level}</span>
        },
        {
            header: 'Status',
            render: (row) => (
                <span className={`px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest ${
                    row.status === 'In Stock' ? 'bg-emerald-50 text-emerald-600 border border-emerald-100' :
                    row.status === 'Low Stock' ? 'bg-amber-50 text-amber-600 border border-amber-100' :
                    'bg-red-50 text-red-600 border border-red-100'
                }`}>
                    {row.status}
                </span>
            )
        },
        {
            header: 'Actions',
            render: (row) => (
                <div className="flex items-center gap-3">
                    <button 
                        onClick={() => {
                            setSelectedProduct(row);
                            setIsDetailsModalOpen(true);
                        }}
                        className="p-2 hover:bg-gray-100 rounded-lg text-blue-500 transition-all" title="View Details">
                        <Eye size={16} />
                    </button>
                    <button 
                        onClick={() => {
                            setSelectedProduct(row);
                            setIsAdjustModalOpen(true);
                        }}
                        className="text-blue-600 text-xs font-black uppercase tracking-widest hover:underline"
                    >
                        Adjust Stock
                    </button>
                </div>
            )
        }
    ];

    const movementColumns = [
        {
            header: 'Date',
            render: (row) => <span className="text-gray-500 font-bold text-xs">{new Date(row.date).toLocaleDateString()}</span>
        },
        {
            header: 'Product / SKU',
            render: (row) => (
                <div className="flex flex-col">
                    <span className="font-bold text-gray-900 text-sm">{row.product_name}</span>
                    <span className="text-[10px] text-gray-400 font-black tracking-widest uppercase">{row.sku}</span>
                </div>
            )
        },
        {
            header: 'Branch',
            render: (row) => <span className="text-gray-400 font-black text-[10px] uppercase tracking-wider">{row.branch}</span>
        },
        {
            header: 'Movement Type',
            render: (row) => <span className="text-gray-700 italic font-black text-xs">{row.reason}</span>
        },
        {
            header: 'Change',
            render: (row) => (
                <span className={`flex items-center gap-1 font-black ${row.change >= 0 ? 'text-emerald-500' : 'text-red-500'}`}>
                    {row.change >= 0 ? <Plus size={12} /> : '-'}
                    {Math.abs(row.change)}
                </span>
            )
        },
        {
            header: 'Stock After',
            render: (row) => <span className="font-black text-gray-900 text-sm">{row.new_stock}</span>
        },
        {
            header: 'Remarks',
            render: (row) => <span className="text-xs text-gray-400 font-bold truncate max-w-[150px]">{row.remarks || '-'}</span>
        }
    ];

    const showToast = (message, type = 'success') => {
        setToast({ message, type });
        setTimeout(() => setToast(null), 3000);
    };



    return (
        <>
            {toast && <Toast message={toast.message} type={toast.type} onClose={() => setToast(null)} />}

            <main className="px-10 py-8 max-w-[1600px] mx-auto space-y-8">
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="w-12 h-12 bg-gray-50 border border-gray-100 rounded-2xl flex items-center justify-center text-gray-400">
                            <Package size={24} />
                        </div>
                        <div>
                            <h1 className="text-3xl font-black text-[#101828] tracking-tight">Inventory Management</h1>
                            <p className="text-gray-500 font-medium text-sm mt-0.5">Track stock, sales, and alerts.</p>
                        </div>
                    </div>
                    
                    <div className="flex items-center gap-4">
                        <button 
                            onClick={() => setIsSaleModalOpen(true)}
                            className="flex items-center gap-2 px-6 py-3 bg-[#10B981] text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-[#059669] transition-all shadow-lg shadow-emerald-100"
                        >
                            <ShoppingCart size={18} />
                            <span>New Sale</span>
                        </button>

                        <button 
                            onClick={() => setIsAddModalOpen(true)}
                            className="flex items-center gap-2 px-6 py-3 bg-[#FF4D4D] text-white rounded-xl font-black text-xs uppercase tracking-widest hover:bg-[#E60000] transition-all shadow-lg shadow-red-100"
                        >
                            <Plus size={18} />
                            <span>Add Product</span>
                        </button>
                    </div>
                </div>

                {/* Tabs */}
                <div className="flex items-center gap-10 border-b border-gray-100">
                    {['Stock Control', 'Reports & Alerts'].map(tab => (
                        <button
                            key={tab}
                            onClick={() => setActiveTab(tab)}
                            className={`pb-4 px-2 text-xs font-black uppercase tracking-[0.2em] transition-all border-b-2 ${
                                activeTab === tab 
                                ? 'border-[#FF4D4D] text-[#FF4D4D]' 
                                : 'border-transparent text-gray-400 hover:text-gray-600'
                            }`}
                        >
                            {tab}
                        </button>
                    ))}
                </div>

                {/* Filters */}
                <div className="flex flex-wrap items-center gap-4">
                    <div className="flex-1 min-w-[300px] relative">
                        <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" size={18} />
                        <input 
                            type="text" 
                            placeholder="Search Product or SKU..."
                            className="w-full pl-12 pr-4 py-3.5 bg-white border border-gray-100 rounded-2xl outline-none focus:ring-2 focus:ring-red-500/10 focus:border-red-500 transition-all text-sm font-bold shadow-sm"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>

                    {!isReceptionist && (
                        <div className="flex items-center gap-2 bg-white border border-gray-100 rounded-2xl p-1.5 shadow-sm">
                            <div className="flex items-center gap-2 px-3 text-gray-400">
                                <Filter size={16} />
                            </div>
                            <select 
                                className="bg-transparent pr-8 py-2 text-xs font-black uppercase tracking-widest outline-none cursor-pointer"
                                value={filterBranch}
                                onChange={(e) => setFilterBranch(e.target.value)}
                            >
                                <option value="">All Branches</option>
                                {branches.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
                            </select>
                            
                            {activeTab === 'Stock Control' && (
                                <>
                                    <div className="w-px h-6 bg-gray-100 mx-2"></div>
                                    <select 
                                        className="bg-transparent pr-8 py-2 text-xs font-black uppercase tracking-widest outline-none cursor-pointer"
                                        value={filterStatus}
                                        onChange={(e) => setFilterStatus(e.target.value)}
                                    >
                                        <option value="">All Statuses</option>
                                        <option value="In Stock">In Stock</option>
                                        <option value="Low Stock">Low Stock</option>
                                        <option value="Out of Stock">Out of Stock</option>
                                    </select>
                                </>
                            )}
                        </div>
                    )}
                    
                    {isReceptionist && activeTab === 'Stock Control' && (
                        <div className="flex items-center gap-2 bg-white border border-gray-100 rounded-2xl p-1.5 shadow-sm">
                            <div className="flex items-center gap-2 px-3 text-gray-400">
                                <Filter size={16} />
                            </div>
                            <select 
                                className="bg-transparent pr-8 py-2 text-xs font-black uppercase tracking-widest outline-none cursor-pointer"
                                value={filterStatus}
                                onChange={(e) => setFilterStatus(e.target.value)}
                            >
                                <option value="">All Statuses</option>
                                <option value="In Stock">In Stock</option>
                                <option value="Low Stock">Low Stock</option>
                                <option value="Out of Stock">Out of Stock</option>
                            </select>
                        </div>
                    )}

                    {(activeTab === 'Product Sales' || activeTab === 'Reports & Alerts') && (
                        <div className="flex items-center gap-3 bg-white border border-gray-100 rounded-2xl p-1.5 shadow-sm px-4">
                            <div className="flex items-center gap-2">
                                <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">From</span>
                                <input 
                                    type="date"
                                    className="bg-transparent text-xs font-black text-gray-700 outline-none"
                                    value={startDate}
                                    onChange={(e) => setStartDate(e.target.value)}
                                />
                            </div>
                            <div className="w-px h-6 bg-gray-100 mx-1"></div>
                            <div className="flex items-center gap-2">
                                <span className="text-[10px] font-black text-gray-400 uppercase tracking-widest">To</span>
                                <input 
                                    type="date"
                                    className="bg-transparent text-xs font-black text-gray-700 outline-none"
                                    value={endDate}
                                    onChange={(e) => setEndDate(e.target.value)}
                                />
                            </div>
                        </div>
                    )}
                </div>

                {activeTab === 'Stock Control' && (
                    <div className="animate-in fade-in slide-in-from-bottom-4 duration-500">
                        <DataTable 
                            columns={stockColumns}
                            data={products.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase()) || p.sku?.toLowerCase().includes(searchTerm.toLowerCase()))}
                            loading={loading}
                            emptyMessage="No products found."
                        />
                    </div>
                )}

                {activeTab === 'Reports & Alerts' && (
                    <div className="bg-white rounded-[32px] border border-gray-100 shadow-sm overflow-hidden animate-in fade-in slide-in-from-bottom-4 duration-500">
                        <div className="p-8 border-b border-gray-100 flex items-center justify-between">
                            <div>
                                <h3 className="text-xl font-black text-gray-900">Inventory Movement Report</h3>
                                <p className="text-xs text-gray-500 font-bold uppercase tracking-widest mt-1">Global audit log of all stock adjustments across all branches.</p>
                            </div>
                            <button 
                                onClick={fetchMovements}
                                className="p-3 bg-gray-50 text-gray-400 rounded-2xl hover:bg-gray-100 transition-all border border-gray-100"
                            >
                                <RefreshCw size={20} className={movementsLoading ? 'animate-spin' : ''} />
                            </button>
                        </div>
                        <DataTable 
                            columns={movementColumns}
                            data={movements}
                            loading={movementsLoading}
                            emptyMessage="No stock movements recorded."
                        />
                    </div>
                )}

                {/* Modals */}
                <AddProductModal 
                    isOpen={isAddModalOpen} 
                    onClose={() => setIsAddModalOpen(false)} 
                    onSave={() => {
                        fetchProducts();
                        showToast('Product added successfully');
                    }}
                    branches={branches}
                    categories={categories}
                />

                <AdjustStockModal 
                    isOpen={isAdjustModalOpen}
                    onClose={() => {
                        setIsAdjustModalOpen(false);
                        setSelectedProduct(null);
                    }}
                    onSave={(p) => {
                        setProducts(prev => prev.map(old => old.id === p.id ? p : old));
                        showToast('Stock adjusted successfully');
                    }}
                    product={selectedProduct}
                />

                <ProductDetailsModal 
                    isOpen={isDetailsModalOpen}
                    onClose={() => {
                        setIsDetailsModalOpen(false);
                        setSelectedProduct(null);
                    }}
                    product={selectedProduct}
                />

                <NewSaleModal 
                    isOpen={isSaleModalOpen}
                    onClose={() => setIsSaleModalOpen(false)}
                    onSave={() => {
                        fetchProducts(); // Refresh stocks
                        showToast('Sale completed successfully');
                    }}
                    branches={branches}
                    products={products}
                />
            </main>
        </>
    );
}
