"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
    MdAdd,
    MdArrowBack,
    MdArrowForward,
    MdDescription,
    MdEvent,
    MdFilterList,
    MdSearch,
    MdSwapVert,
} from "react-icons/md";
import toast from "react-hot-toast";
import {
    purchaseOrderService,
    stockAdjustmentsService,
} from "@/services/api";
import {
    StockAdjustment,
    StockAdjustmentListMeta,
    StockAdjustmentType,
    StockAdjustmentTypeFilter,
    StockAdjustmentVoidFilter,
    STOCK_ADJUSTMENT_TYPE_LABELS,
} from "@/types/stock-adjustment";
import { formatDateTime } from "@/utils/dateUtils";
import DateFilterPopover from "@/components/ui/DateFilterPopover";
import TextInputModal from "@/components/ui/TextInputModal";
import StockAdjustmentsFilterPopover from "./StockAdjustmentsFilterPopover";
import NewStockAdjustmentModal from "./NewStockAdjustmentModal";

const DEFAULT_LIMIT = 20;

const StockAdjustmentsPage: React.FC = () => {
    const [adjustments, setAdjustments] = useState<StockAdjustment[]>([]);
    const [meta, setMeta] = useState<StockAdjustmentListMeta>({
        currentPage: 1,
        itemsPerPage: DEFAULT_LIMIT,
        totalItems: 0,
        totalPages: 1,
        hasNextPage: false,
        hasPreviousPage: false,
    });
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const [warehouses, setWarehouses] = useState<Array<{ id: number; name: string }>>(
        []
    );

    const [search, setSearch] = useState("");
    const [searchInput, setSearchInput] = useState("");
    const [voidedFilter, setVoidedFilter] =
        useState<StockAdjustmentVoidFilter>("active");
    const [typeFilter, setTypeFilter] =
        useState<StockAdjustmentTypeFilter>("all");
    const [warehouseId, setWarehouseId] = useState<number | null>(null);
    const [startDate, setStartDate] = useState<string | null>(null);
    const [endDate, setEndDate] = useState<string | null>(null);

    const [isFilterOpen, setIsFilterOpen] = useState(false);
    const [isDateFilterOpen, setIsDateFilterOpen] = useState(false);
    const [isNewModalOpen, setIsNewModalOpen] = useState(false);
    const [voidTarget, setVoidTarget] = useState<StockAdjustment | null>(null);

    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(DEFAULT_LIMIT);

    const fetch = useCallback(async () => {
        try {
            setLoading(true);
            setError(null);
            const response = await stockAdjustmentsService.list({
                page,
                limit,
                search: search || undefined,
                voided: voidedFilter,
                adjustmentType: typeFilter === "all" ? undefined : typeFilter,
                warehouseId: warehouseId ?? undefined,
                startDate: startDate || undefined,
                endDate: endDate || undefined,
            });
            setAdjustments(response.data.data || []);
            setMeta(response.data.meta);
        } catch (err: any) {
            console.error("Failed to fetch stock adjustments", err);
            setError(
                err.response?.data?.message ||
                "Failed to load stock adjustments. Please try again."
            );
        } finally {
            setLoading(false);
        }
    }, [page, limit, search, voidedFilter, typeFilter, warehouseId, startDate, endDate]);

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

    useEffect(() => {
        purchaseOrderService
            .getAllWarehouses()
            .then((res) => setWarehouses(res.data || []))
            .catch(() => {
                /* silent — only used for the filter popover */
            });
    }, []);

    useEffect(() => {
        const t = setTimeout(() => {
            if (searchInput !== search) {
                setSearch(searchInput);
                setPage(1);
            }
        }, 350);
        return () => clearTimeout(t);
    }, [searchInput, search]);

    const dateFilterCount = useMemo(
        () => (startDate ? 1 : 0) + (endDate ? 1 : 0),
        [startDate, endDate]
    );

    const filterCount = useMemo(() => {
        let count = 0;
        if (voidedFilter !== "active") count += 1;
        if (typeFilter !== "all") count += 1;
        if (warehouseId !== null) count += 1;
        return count;
    }, [voidedFilter, typeFilter, warehouseId]);

    const handleApplyFilters = (filters: {
        voided: StockAdjustmentVoidFilter;
        adjustmentType: StockAdjustmentTypeFilter;
        warehouseId: number | null;
    }) => {
        setVoidedFilter(filters.voided);
        setTypeFilter(filters.adjustmentType);
        setWarehouseId(filters.warehouseId);
        setPage(1);
    };

    const handleApplyDateFilter = (
        start: string | null,
        end: string | null
    ) => {
        setStartDate(start);
        setEndDate(end);
        setPage(1);
    };

    const handleVoidSubmit = async (reason: string) => {
        if (!voidTarget) return;
        try {
            await stockAdjustmentsService.void(voidTarget.id, reason);
            toast.success("Adjustment voided.");
            setVoidTarget(null);
            fetch();
        } catch (err: any) {
            toast.error(err.response?.data?.message || "Failed to void adjustment.");
        }
    };

    const startItem = meta.totalItems === 0 ? 0 : (page - 1) * limit + 1;
    const endItem = Math.min(page * limit, meta.totalItems);

    return (
        <>
            {/* Sticky Header */}
            <div className="sticky top-0 z-30 bg-gradient-to-l from-white to-[#DFF9FF] shadow-sm border-b border-gray-200">
                <div className="px-4 md:px-6 py-4 flex items-center justify-between flex-wrap gap-3">
                    <h1 className="text-xl md:text-2xl font-bold text-gray-800">
                        Stock Adjustments
                    </h1>
                    <button
                        onClick={() => setIsNewModalOpen(true)}
                        className="inline-flex items-center gap-2 bg-[#3997E0] text-white px-4 py-2 rounded-xl text-sm hover:bg-blue-700"
                    >
                        <MdAdd size={18} />
                        New Adjustment
                    </button>
                </div>
            </div>

            <div className="m-4 md:m-6">
                <div className="bg-white rounded-lg shadow-[0px_4px_34px_0px_rgba(0,59,113,0.16)]">
                    {/* Search + Filters */}
                    <div className="p-4 md:p-6 flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0 md:space-x-4">
                        <div className="flex items-center bg-gray-100 p-2 rounded-md w-full md:w-1/3">
                            <MdSearch size={20} color="#6B7280" className="mr-2" />
                            <input
                                type="text"
                                placeholder="Search product, warehouse, reason, reference..."
                                value={searchInput}
                                onChange={(e) => setSearchInput(e.target.value)}
                                className="bg-transparent outline-none w-full text-sm text-gray-700 placeholder-gray-500"
                            />
                        </div>
                        <div className="flex items-center space-x-4">
                            <button
                                className="flex items-center text-gray-600 hover:text-gray-800 text-sm bg-gray-100 p-2 rounded-md relative"
                                onClick={() => setIsFilterOpen(true)}
                            >
                                <MdFilterList size={20} className="mr-2" />
                                Filters
                                {filterCount > 0 && (
                                    <span className="absolute -top-2 -right-2 bg-blue-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                                        {filterCount}
                                    </span>
                                )}
                            </button>
                            <button
                                className="flex items-center text-gray-600 hover:text-gray-800 text-sm bg-gray-100 p-2 rounded-md relative"
                                onClick={() => setIsDateFilterOpen(true)}
                            >
                                <MdEvent size={20} className="mr-2" />
                                Date Filter
                                {dateFilterCount > 0 && (
                                    <span className="absolute -top-2 -right-2 bg-blue-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                                        {dateFilterCount}
                                    </span>
                                )}
                            </button>
                        </div>
                    </div>

                    {/* Body */}
                    {loading ? (
                        <div className="flex justify-center items-center py-16">
                            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3" />
                            <span className="text-gray-600">Loading adjustments...</span>
                        </div>
                    ) : error ? (
                        <div className="p-6 bg-red-100 text-red-700 m-4 rounded-md">
                            <p className="font-medium">Error</p>
                            <p>{error}</p>
                        </div>
                    ) : adjustments.length === 0 ? (
                        <div className="p-12 text-center">
                            <MdSwapVert className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                            <p className="text-gray-500 text-lg">No stock adjustments yet</p>
                            <p className="text-gray-400 text-sm mb-4">
                                Use New Adjustment to record initial stock or correct existing
                                quantities.
                            </p>
                        </div>
                    ) : (
                        <>
                            {/* Desktop Table */}
                            <div className="hidden lg:block overflow-x-auto">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                Date
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                Warehouse
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                Product
                                            </th>
                                            <th className="px-6 py-3 text-right text-xs font-bold text-black uppercase tracking-wider">
                                                Qty
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                Type
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                By
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-black uppercase tracking-wider">
                                                Status
                                            </th>
                                            <th className="px-6 py-3"></th>
                                        </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                        {adjustments.map((a, idx) => (
                                            <tr
                                                key={a.id}
                                                className={`${idx % 2 === 0 ? "bg-white" : "bg-[#F2F9FF]"} hover:bg-gray-100 transition-colors`}
                                            >
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                    {formatDateTime(a.createdAt)}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                    {a.warehouseName || "—"}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-800 font-medium">
                                                    {a.productName || "—"}
                                                </td>
                                                <td
                                                    className={`px-6 py-4 whitespace-nowrap text-sm text-right font-mono font-semibold ${
                                                        a.quantityChange > 0
                                                            ? "text-green-700"
                                                            : "text-red-700"
                                                    }`}
                                                >
                                                    {a.quantityChange > 0
                                                        ? `+${a.quantityChange}`
                                                        : a.quantityChange}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                    {STOCK_ADJUSTMENT_TYPE_LABELS[a.adjustmentType]}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                                                    {a.createdBy
                                                        ? `${a.createdBy.firstname} ${a.createdBy.lastname || ""}`.trim()
                                                        : "—"}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap">
                                                    {a.isVoided ? (
                                                        <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-200 text-gray-700">
                                                            Voided
                                                        </span>
                                                    ) : (
                                                        <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                                                            Active
                                                        </span>
                                                    )}
                                                </td>
                                                <td className="px-6 py-4 whitespace-nowrap text-right">
                                                    {!a.isVoided && (
                                                        <button
                                                            onClick={() => setVoidTarget(a)}
                                                            className="text-sm text-red-600 hover:text-red-800 font-medium"
                                                        >
                                                            Void
                                                        </button>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>

                            {/* Mobile Card */}
                            <div className="lg:hidden space-y-3 p-4">
                                {adjustments.map((a) => (
                                    <div
                                        key={a.id}
                                        className="bg-white border border-gray-200 rounded-lg p-4"
                                    >
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-sm font-medium text-gray-800">
                                                {a.productName}
                                            </span>
                                            <span
                                                className={`font-mono font-semibold text-sm ${
                                                    a.quantityChange > 0
                                                        ? "text-green-700"
                                                        : "text-red-700"
                                                }`}
                                            >
                                                {a.quantityChange > 0
                                                    ? `+${a.quantityChange}`
                                                    : a.quantityChange}
                                            </span>
                                        </div>
                                        <div className="text-xs text-gray-500 space-y-1">
                                            <div>
                                                {a.warehouseName} ·{" "}
                                                {STOCK_ADJUSTMENT_TYPE_LABELS[a.adjustmentType]}
                                            </div>
                                            <div>
                                                {formatDateTime(a.createdAt)}
                                                {a.createdBy &&
                                                    ` · ${a.createdBy.firstname} ${a.createdBy.lastname || ""}`.trim()}
                                            </div>
                                            {a.reason && (
                                                <div className="text-gray-700 mt-1">{a.reason}</div>
                                            )}
                                        </div>
                                        <div className="flex items-center justify-between mt-2 pt-2 border-t border-gray-100">
                                            {a.isVoided ? (
                                                <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-gray-200 text-gray-700">
                                                    Voided
                                                </span>
                                            ) : (
                                                <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-green-100 text-green-800">
                                                    Active
                                                </span>
                                            )}
                                            {!a.isVoided && (
                                                <button
                                                    onClick={() => setVoidTarget(a)}
                                                    className="text-sm text-red-600 hover:text-red-800 font-medium"
                                                >
                                                    Void
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>

                            {/* Pagination */}
                            <div className="px-4 lg:px-6 py-4 border-t border-gray-200 flex flex-col lg:flex-row lg:justify-between lg:items-center gap-3">
                                <div className="flex items-center gap-2 text-sm text-gray-600">
                                    <select
                                        value={limit}
                                        onChange={(e) => {
                                            setLimit(Number(e.target.value));
                                            setPage(1);
                                        }}
                                        className="border border-gray-300 rounded-md px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500 bg-white text-sm"
                                    >
                                        <option value={10}>10</option>
                                        <option value={20}>20</option>
                                        <option value={50}>50</option>
                                        <option value={100}>100</option>
                                    </select>
                                    <span>per page</span>
                                    <span className="ml-3">
                                        {startItem}-{endItem} of {meta.totalItems}
                                    </span>
                                </div>
                                <div className="flex items-center gap-1">
                                    <button
                                        onClick={() => setPage((p) => Math.max(1, p - 1))}
                                        disabled={!meta.hasPreviousPage}
                                        className="px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-1"
                                    >
                                        <MdArrowBack size={16} />
                                        Prev
                                    </button>
                                    <span className="text-sm text-gray-600 px-2">
                                        Page {meta.currentPage} of {meta.totalPages}
                                    </span>
                                    <button
                                        onClick={() =>
                                            setPage((p) => Math.min(meta.totalPages, p + 1))
                                        }
                                        disabled={!meta.hasNextPage}
                                        className="px-3 py-1.5 text-sm rounded-md border border-gray-300 text-gray-700 hover:bg-gray-100 disabled:opacity-40 disabled:cursor-not-allowed inline-flex items-center gap-1"
                                    >
                                        Next
                                        <MdArrowForward size={16} />
                                    </button>
                                </div>
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* Filters */}
            <StockAdjustmentsFilterPopover
                isOpen={isFilterOpen}
                onClose={() => setIsFilterOpen(false)}
                onApply={handleApplyFilters}
                initialFilters={{
                    voided: voidedFilter,
                    adjustmentType: typeFilter,
                    warehouseId,
                }}
                warehouseOptions={warehouses}
            />

            <DateFilterPopover
                isOpen={isDateFilterOpen}
                onClose={() => setIsDateFilterOpen(false)}
                onApply={handleApplyDateFilter}
                initialStartDate={startDate}
                initialEndDate={endDate}
                showDateRangeInfo={true}
            />

            {/* New Adjustment Modal */}
            <NewStockAdjustmentModal
                isOpen={isNewModalOpen}
                onClose={() => setIsNewModalOpen(false)}
                onSaved={fetch}
            />

            {/* Void Modal */}
            {voidTarget && (
                <TextInputModal
                    isOpen={true}
                    onClose={() => setVoidTarget(null)}
                    onConfirm={handleVoidSubmit}
                    title="Void Stock Adjustment"
                    description={`Reverse ${voidTarget.quantityChange > 0 ? "+" : ""}${voidTarget.quantityChange} ${voidTarget.productName} on ${voidTarget.warehouseName}? A compensating entry will be recorded with the reason below.`}
                    placeholder="e.g. Entered on the wrong warehouse"
                    confirmText="Void"
                    cancelText="Cancel"
                    required={true}
                    multiline={true}
                />
            )}
        </>
    );
};

export default StockAdjustmentsPage;
