import React, { useEffect, useState } from 'react';
import { getProducts, deleteProduct, logout } from '../api';
import { Link, useNavigate } from 'react-router-dom';
import { Plus, Search, Trash2, Edit, LogOut, Package, Image as ImageIcon, ChevronLeft, ChevronRight } from 'lucide-react';

export default function ProductList() {
    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [search, setSearch] = useState('');
    const [error, setError] = useState('');
    const [viewMode, setViewMode] = useState('table');
    const navigate = useNavigate();

    const fetchProducts = async () => {
        setLoading(true);
        try {
            const data = await getProducts(page, search);
            setProducts(data);
            setError('');
        } catch (err) {
            console.error(err);
            if (err.message === 'Not logged in') {
                navigate('/');
            } else {
                setError('Failed to load products.');
            }
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchProducts();
    }, [page]); // Re-fetch when page changes

    // Search effect with debounce could be added, but manual search button for now or just simple effect
    const handleSearch = (e) => {
        e.preventDefault();
        setPage(1);
        fetchProducts();
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this product?')) {
            try {
                await deleteProduct(id);
                fetchProducts(); // Refresh
            } catch (err) {
                alert('Failed to delete product');
            }
        }
    };

    const handleLogout = () => {
        logout();
        navigate('/');
    };

    return (
        <div className="min-h-screen bg-gray-900 text-gray-100">
            {/* Navbar */}
            <nav className="bg-gray-800 border-b border-gray-700">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div className="flex items-center justify-between h-16">
                        <div className="flex items-center">
                            <span className="text-xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-teal-400">
                                Inventory Manager
                            </span>
                        </div>
                        <div className="flex items-center space-x-4">
                            <div className="bg-gray-700 rounded-lg p-1 flex">
                                <button
                                    onClick={() => setViewMode('table')}
                                    className={`p-2 rounded-md transition ${viewMode === 'table' ? 'bg-gray-600 text-white shadow-sm' : 'text-gray-400 hover:text-white'}`}
                                    title="Table View"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" /></svg>
                                </button>
                                <button
                                    onClick={() => setViewMode('grid')}
                                    className={`p-2 rounded-md transition ${viewMode === 'grid' ? 'bg-gray-600 text-white shadow-sm' : 'text-gray-400 hover:text-white'}`}
                                    title="Grid View"
                                >
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z" /></svg>
                                </button>
                            </div>
                            <button onClick={handleLogout} className="flex items-center text-gray-400 hover:text-white transition">
                                <LogOut className="h-5 w-5 mr-1" />
                                Logout
                            </button>
                        </div>
                    </div>
                </div>
            </nav>

            {/* Main Content */}
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* Header Actions */}
                <div className="flex flex-col sm:flex-row justify-between items-center mb-8 gap-4">
                    <form onSubmit={handleSearch} className="relative w-full sm:w-96">
                        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <Search className="h-5 w-5 text-gray-500" />
                        </div>
                        <input
                            type="text"
                            placeholder="Search products..."
                            className="block w-full pl-10 bg-gray-800 border-gray-700 rounded-lg py-2 text-white placeholder-gray-400 focus:ring-2 focus:ring-blue-500 outline-none"
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                        />
                    </form>

                    <Link
                        to="/product/new"
                        className="flex items-center bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition"
                    >
                        <Plus className="h-5 w-5 mr-1" />
                        Add Product
                    </Link>
                </div>

                {/* Error */}
                {error && (
                    <div className="bg-red-900/50 border border-red-500 text-red-200 p-4 rounded-lg mb-6">
                        {error}
                    </div>
                )}

                {loading ? (
                    <div className="text-center py-20 text-gray-400">Loading products...</div>
                ) : products.length === 0 ? (
                    <div className="text-center py-20 text-gray-400">No products found.</div>
                ) : (
                    <>
                        {viewMode === 'table' ? (
                            <div className="bg-gray-800 rounded-xl shadow-xl overflow-hidden border border-gray-700">
                                <div className="overflow-x-auto">
                                    <table className="min-w-full divide-y divide-gray-700">
                                        <thead className="bg-gray-750">
                                            <tr>
                                                <th className="px-6 py-4 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Product</th>
                                                <th className="px-6 py-4 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Price</th>
                                                <th className="px-6 py-4 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Stock</th>
                                                <th className="px-6 py-4 text-left text-xs font-medium text-gray-400 uppercase tracking-wider">Status</th>
                                                <th className="px-6 py-4 text-right text-xs font-medium text-gray-400 uppercase tracking-wider">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-700">
                                            {products.map((product) => (
                                                <tr key={product.id} className="hover:bg-gray-750 transition">
                                                    <td className="px-6 py-4 whitespace-nowrap">
                                                        <div className="flex items-center">
                                                            <div className="h-16 w-16 flex-shrink-0 bg-gray-700 rounded-md overflow-hidden flex items-center justify-center border border-gray-600">
                                                                {product.images?.[0]?.src ? (
                                                                    <img className="h-full w-full object-cover" src={product.images[0].src} alt="" />
                                                                ) : (
                                                                    <ImageIcon className="h-6 w-6 text-gray-500" />
                                                                )}
                                                            </div>
                                                            <div className="ml-4">
                                                                <div className="text-sm font-medium text-white max-w-xs truncate" title={product.name}>{product.name}</div>
                                                                <div className="text-sm text-gray-500">ID: {product.id}</div>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap">
                                                        <div className="text-sm text-gray-300">
                                                            <span dangerouslySetInnerHTML={{ __html: product.price_html || ('$' + product.price) }} />
                                                        </div>
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap">
                                                        <div className="text-sm text-gray-300">
                                                            {product.manage_stock ? product.stock_quantity : 'Unlimited'}
                                                        </div>
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap">
                                                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${product.stock_status === 'instock' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
                                                            }`}>
                                                            {product.stock_status}
                                                        </span>
                                                    </td>
                                                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                        <Link to={`/product/${product.id}`} className="text-blue-400 hover:text-blue-300 mr-4">
                                                            <Edit className="h-5 w-5 inline" />
                                                        </Link>
                                                        <button onClick={() => handleDelete(product.id)} className="text-red-400 hover:text-red-300">
                                                            <Trash2 className="h-5 w-5 inline" />
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                                {products.map((product) => (
                                    <div key={product.id} className="bg-gray-800 rounded-xl shadow-lg border border-gray-700 overflow-hidden hover:shadow-xl transition flex flex-col">
                                        <div className="h-48 bg-gray-700 overflow-hidden relative">
                                            {product.images?.[0]?.src ? (
                                                <img className="w-full h-full object-cover" src={product.images[0].src} alt="" />
                                            ) : (
                                                <div className="w-full h-full flex items-center justify-center text-gray-500">
                                                    <ImageIcon className="h-10 w-10" />
                                                </div>
                                            )}
                                            <div className="absolute top-2 right-2 flex space-x-1">
                                                <span className={`px-2 py-1 text-xs font-semibold rounded-full shadow-sm ${product.stock_status === 'instock' ? 'bg-green-100/90 text-green-800' : 'bg-red-100/90 text-red-800'
                                                    }`}>
                                                    {product.stock_status === 'instock' ? 'In Stock' : 'Out'}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="p-4 flex-1 flex flex-col">
                                            <div className="flex justify-between items-start mb-2">
                                                <h3 className="text-lg font-bold text-white line-clamp-2" title={product.name}>{product.name}</h3>
                                            </div>
                                            <p className="text-sm text-gray-400 mb-4">ID: {product.id}</p>
                                            <div className="mt-auto flex items-center justify-between">
                                                <span className="text-lg font-semibold text-blue-300" dangerouslySetInnerHTML={{ __html: product.price_html || ('$' + product.price) }} />
                                                <div className="flex space-x-3">
                                                    <Link to={`/product/${product.id}`} className="text-gray-400 hover:text-blue-400 transition">
                                                        <Edit className="h-5 w-5" />
                                                    </Link>
                                                    <button onClick={() => handleDelete(product.id)} className="text-gray-400 hover:text-red-400 transition">
                                                        <Trash2 className="h-5 w-5" />
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </>
                )}


                {/* Pagination */}
                <div className="flex items-center justify-between mt-6">
                    <button
                        onClick={() => setPage(p => Math.max(1, p - 1))}
                        disabled={page === 1}
                        className="flex items-center text-gray-400 hover:text-white disabled:opacity-50"
                    >
                        <ChevronLeft className="h-5 w-5 mr-1" />
                        Previous
                    </button>
                    <span className="text-gray-400">Page {page}</span>
                    <button
                        onClick={() => setPage(p => p + 1)}
                        className="flex items-center text-gray-400 hover:text-white"
                    >
                        Next
                        <ChevronRight className="h-5 w-5 ml-1" />
                    </button>
                </div>
            </main>
        </div>
    );
}
