import Tabs from "../../components/Tabs";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import IconBox from "../../components/Icon/IconBox";
import MiniDashboard from "../../components/MiniDashboard";
import IconInStock from "../../components/Icon/IconInStock";
import IconLowStock from "../../components/Icon/IconLowStock";
import IconChevronLeft from "../../components/Icon/IconChevronLeft";
import IconChevronRight from "../../components/Icon/IconChevronRight";
import IconSearch from "../../components/Icon/IconSearch";
import api from '../../api/axios';
import { toast } from 'react-toastify';

// Updated interface to match backend response
interface StockItem {
    id: string;
    batch: {
        id: number;
        name: string;
    };
    course: {
        name: string;
    };
    material: {
        id: number;
        name: string;
        category: string;
        unit: string;
    };
    stock_count: number;
    student_count: number;
    stock_out: number;
    stock_in: number;
    consumed: number;
    last_updated: string;
}

// Updated interface to match backend summary
interface Summary {
    total_stock_out: number;
    total_stock_in: number;
    total_consumed: number;
}

interface PaginationData {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    next_page_url: string | null;
    prev_page_url: string | null;
}

function StockInOut() {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [stockData, setStockData] = useState<StockItem[]>([]);
    const [summary, setSummary] = useState<Summary>({
        total_stock_out: 0,
        total_stock_in: 0,
        total_consumed: 0,
    });
    const [search, setSearch] = useState('');
    const [perPage, setPerPage] = useState(25);

    const [pagination, setPagination] = useState<PaginationData>({
        current_page: 1,
        last_page: 1,
        per_page: 25,
        total: 0,
        next_page_url: null,
        prev_page_url: null
    });

    const tabData = [
        { id: 'Stock', label: 'Stock', path: '/manage_inventory' },
        { id: 'Stock In / Out', label: 'Stock In / Out', path: '/manage_stock_in_out' },
        { id: 'Assets', label: 'Assets', path: '/manage_inventory_asset' },
        { id: 'Tickets', label: 'Tickets', path: '/manage_tickets' },
    ];

    useEffect(() => {
        fetchStockData();
    }, [pagination.current_page, perPage]);

    const fetchStockData = async (searchValue = search) => {
        setLoading(true);
        try {
            const params: any = {};
             if (searchValue) params.search  = search;

            const response = await api.get('/inventory/stock-in-out', { params });

            if (response.data.success) {
                setStockData(response.data.data);
                setSummary(response.data.summary);

                setPagination(prev => ({
                    ...prev,
                    total: response.data.data.length,
                    last_page: Math.ceil(response.data.data.length / perPage)
                }));
            }
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Failed to fetch stock data');
            console.error('Error fetching stock data:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
        setSearch(e.target.value);
        fetchStockData(e.target.value);
    };


    const handleClearFilters = () => {
        setSearch('');
        setPagination(prev => ({ ...prev, current_page: 1 }));
        fetchStockData();
    };

    const handlePageChange = (page: number) => {
        if (page < 1 || page > pagination.last_page) return;
        setPagination(prev => ({ ...prev, current_page: page }));
    };

    const handlePerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newPerPage = parseInt(e.target.value);
        setPerPage(newPerPage);
        setPagination(prev => ({
            ...prev,
            per_page: newPerPage,
            current_page: 1
        }));
    };


    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleDateString('en-GB', {
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        });
    };

    // Dashboard data from API summary
    const dashboardData = [
        {
            title: "Total Stock Out",
            value: summary.total_stock_out.toString(),
            icon: <IconLowStock className="w-5 h-5"/>,
            bgColor: "bg-red-100",
            iconColor: "text-red-600",
        },
        {
            title: "Total Stock In",
            value: summary.total_stock_in.toString(),
            icon: <IconInStock className="w-5 h-5"/>,
            bgColor: "bg-green-100",
            iconColor: "text-green-600",
        },
        {
            title: "Net Consumed",
            value: summary.total_consumed.toString(),
            icon: <IconBox className="w-5 h-5"/>,
            bgColor: "bg-blue-100",
            iconColor: "text-blue-600",
        }
    ];

    // Table Skeleton Loader
    const TableSkeleton = () => (
        <>
            {[...Array(5)].map((_, index) => (
                <tr key={index} className="animate-pulse border-b border-gray-100">
                    <td className="px-6 py-4">
                        <div className="h-4 w-24 bg-gray-200 rounded"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-32 bg-gray-200 rounded mb-2"></div>
                        <div className="h-3 w-20 bg-gray-200 rounded"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-28 bg-gray-200 rounded mb-2"></div>
                        <div className="h-5 w-16 bg-gray-200 rounded-full"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-12 bg-gray-200 rounded"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-20 bg-gray-200 rounded"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-20 bg-gray-200 rounded"></div>
                    </td>
                    <td className="px-6 py-4">
                        <div className="h-4 w-20 bg-gray-200 rounded"></div>
                    </td>
                </tr>
            ))}
        </>
    );

    // Pagination Component
    const PaginationComponent = () => {
        const pages = [];
        const maxVisible = 5;
        let startPage = Math.max(1, pagination.current_page - Math.floor(maxVisible / 2));
        let endPage = Math.min(pagination.last_page, startPage + maxVisible - 1);

        if (endPage - startPage + 1 < maxVisible) {
            startPage = Math.max(1, endPage - maxVisible + 1);
        }

        for (let i = startPage; i <= endPage; i++) {
            pages.push(i);
        }

        return (
            <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6 pt-4 border-t border-gray-200">
                <div className="text-sm text-gray-600 flex items-center gap-3">
                    <span>
                        Showing {((pagination.current_page - 1) * pagination.per_page) + 1} to{' '}
                        {Math.min(pagination.current_page * pagination.per_page, pagination.total)} of{' '}
                        {pagination.total} entries
                    </span>
                    <select
                        value={perPage}
                        onChange={handlePerPageChange}
                        className="px-2 py-1 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                        <option value={10}>10</option>
                        <option value={25}>25</option>
                        <option value={50}>50</option>
                        <option value={100}>100</option>
                    </select>
                </div>
                <div className="flex gap-2">
                    <button
                        onClick={() => handlePageChange(pagination.current_page - 1)}
                        disabled={pagination.current_page === 1}
                        className="w-8 h-8 flex items-center justify-center border rounded-full disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                    >
                        <IconChevronLeft className="w-4 h-4" />
                    </button>
                    <div className="flex gap-1">
                        {pages.map((pageNum) => (
                            <button
                                key={pageNum}
                                onClick={() => handlePageChange(pageNum)}
                                className={`w-8 h-8 flex items-center justify-center border rounded-full transition-colors ${
                                    pagination.current_page === pageNum
                                        ? 'bg-primary text-white border-primary'
                                        : 'hover:bg-gray-50'
                                }`}
                            >
                                {pageNum}
                            </button>
                        ))}
                    </div>
                    <button
                        onClick={() => handlePageChange(pagination.current_page + 1)}
                        disabled={pagination.current_page === pagination.last_page}
                        className="w-8 h-8 flex items-center justify-center border rounded-full hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <IconChevronRight className="w-4 h-4" />
                    </button>
                </div>
            </div>
        );
    };

    return (
        <>
            <div className="flex items-center justify-between gap-2 mb-2 flex-wrap">
                <ul className="flex space-x-2 items-center">
                    <li>
                        <Link to="/manage_inventory" className="text-primary text-lg hover:underline">
                            Inventory Management
                        </Link>
                    </li>
                </ul>
            </div>

            <Tabs
                tabs={tabData}
                defaultTab="Stock In / Out"
                onChange={(tabId) => {
                    const selectedTab = tabData.find(t => t.id === tabId);
                    if (selectedTab?.path) {
                        navigate(selectedTab.path);
                    }
                }}
            />

            <div className="pt-4">
                <div className="p-4 rounded-xl shadow-md bg-white w-full max-w-full overflow-hidden">

                    {/* Mini Dashboard */}
                    <div className="col-span-12 mb-6">
                        <MiniDashboard data={dashboardData} />
                    </div>

                    {/* Filters Section */}
                    <div className="relative mb-4">
                        <input
                            type="text"
                            placeholder="Search items, batches..."
                            value={search}
                            onChange={handleSearch}
                            className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                        />
                        <IconSearch className="absolute left-3 top-2.5 w-5 h-5 text-gray-400" />
                    </div>

                    {/* Stock Table */}
                    <div className="col-span-12 overflow-x-auto">
                        <table className="min-w-full divide-y divide-gray-200">
                            <thead className="bg-gray-50">
                                <tr>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Date
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Item / Category
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Course / Batch
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Students
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Stock Out
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Stock In
                                    </th>
                                    <th className="text-left px-4 py-3 font-black text-md text-[#495057]">
                                        Net Consumed
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                                {loading ? (
                                    <TableSkeleton />
                                ) : stockData.length === 0 ? (
                                    <tr>
                                        <td colSpan={7} className="px-6 py-12 text-center">
                                            <IconBox className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                                            <p className="text-lg text-gray-500">No stock transactions found</p>
                                            <p className="text-sm text-gray-400 mt-1">Try adjusting your search or filters</p>
                                        </td>
                                    </tr>
                                ) : (
                                    stockData.map((item) => (
                                        <tr key={item.id} className="hover:bg-gray-50 transition-colors">
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                {formatDate(item.last_updated)}
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex flex-col">
                                                    <div className="text-sm font-medium text-gray-900">
                                                        {item.material.name}
                                                    </div>
                                                    <div className="text-sm text-gray-500">
                                                        {item.material.category}
                                                    </div>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4">
                                                <div className="flex flex-col">
                                                    <div className="text-sm font-medium text-gray-900">
                                                        {item.course.name}
                                                    </div>
                                                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 mt-1 w-fit">
                                                        {item.batch.name}
                                                    </span>
                                                </div>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                {item.student_count}
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className="text-red-600 font-medium text-sm">
                                                    -{item.stock_out} {item.material.unit}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className="text-green-600 font-medium text-sm">
                                                    +{item.stock_in} {item.material.unit}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 whitespace-nowrap">
                                                <span className="font-semibold text-sm text-gray-900">
                                                    {item.consumed} {item.material.unit}
                                                </span>
                                            </td>
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>

                    {/* Pagination */}
                    {!loading && stockData.length > 0 && <PaginationComponent />}
                </div>
            </div>
        </>
    );
}

export default StockInOut;
