import { closestCenter, DndContext } from "@dnd-kit/core";
import { restrictToParentElement } from "@dnd-kit/modifiers";
import {
    Box,
    Button,
    Dialog,
    DialogContent,
    DialogTitle,
    Typography,
    useTheme
} from "@mui/material";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { DroppableContainer } from "./DroppableContainer";
import SortableItem from "./SortableItem";
import OrderType, { OrderStatusEnum } from "../../components/Order";

const mockOrders: OrderType[] = [
    {
        id: "1001",
        date: "2025-05-20",
        status: OrderStatusEnum.CANCELLED,
        items: [
            { name: "Tomatensamen", quantity: 2, price: 3.99 },
            { name: "Blumenerde", quantity: 1, price: 7.49 }
        ],
        total: 15.47,
        address: "Musterstraße 1, 12345 Musterstadt"
    },
    {
        id: "1000",
        date: "2025-05-10",
        status: OrderStatusEnum.ISSUES,
        items: [{ name: "Gießkanne", quantity: 1, price: 12.99 }],
        total: 12.99,
        address: "Musterstraße 1, 12345 Musterstadt"
    },
    {
        id: "1002",
        date: "2025-05-15",
        status: OrderStatusEnum.DELIVERED,
        items: [{ name: "Pflanzendünger", quantity: 1, price: 8.99 }],
        total: 8.99,
        address: "Musterstraße 1, 12345 Musterstadt"
    },
    {
        id: "1003",
        date: "2025-05-18",
        status: OrderStatusEnum.ORDERED,
        items: [{ name: "Blumentopf", quantity: 2, price: 5.99 }],
        total: 11.98,
        address: "Musterstraße 1, 12345 Musterstadt"
    },
    {
        id: "1004",
        date: "2025-05-18",
        status: OrderStatusEnum.IN_PROGRESS,
        items: [{ name: "TimWall", quantity: 2, price: 5.99 }],
        total: 12.99,
        address: "Musterstraße 1, 12345 Musterstadt"
    }
];

const statusOrder: OrderStatusEnum[] = [
  OrderStatusEnum.CANCELLED,
  OrderStatusEnum.ISSUES,
  OrderStatusEnum.ORDERED,
  OrderStatusEnum.IN_PROGRESS,
    OrderStatusEnum.DELIVERED
];

export default function OrdersInfo() {
    const { t } = useTranslation();
    const theme = useTheme();
    const [orders, setOrders] = useState<OrderType[]>(mockOrders);
    const [selectedOrder, setSelectedOrder] = useState<OrderType | null>(null);

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const handleDragEnd = (event: any) => {
        const { active, over } = event;
        if (!over || active.id === over.id) return;

        const newStatus = over.id;
        setOrders((prev) =>
            prev.map((order) =>
                order.id === active.id ? { ...order, status: newStatus } : order
            )
        );
    };

    const handleNextStatus = (order: OrderType) => {
        const currentIndex = statusOrder.indexOf(order.status);
        if (currentIndex < statusOrder.length - 1) {
            setOrders((prev) =>
                prev.map((o) =>
                    o.id === order.id
                        ? { ...o, status: statusOrder[currentIndex + 1] as OrderType["status"] }
                        : o
                )
            );
        }
    };

    const renderOrders = (status: OrderStatusEnum) => {
        const filtered = orders.filter((o) => o.status === status);

        return (
            <Box
                sx={{
                    minHeight: 300,
                    p: 2,
                    bgcolor: theme.palette.background.paper,
                    border: `1px solid ${theme.palette.divider}`,
                    borderRadius: 2
                }}
            >
                <Typography
                    variant="h6"
                    align="center"
                    gutterBottom
                    sx={{ color: theme.palette.text.primary }}
                >
                    {t(status.toString())}
                </Typography>
                {filtered.map((order) => (
                    <SortableItem
                        key={order.id}
                        id={order.id}
                        order={order}
                        onClick={() => setSelectedOrder(order)}
                    />
                ))}
            </Box>
        );
    };

    return (
        <Box>
            <Typography variant="h4" align="center" gutterBottom>
                {t("Orders Management")}
            </Typography>

            <DndContext
                collisionDetection={closestCenter}
                onDragEnd={handleDragEnd}
                modifiers={[restrictToParentElement]}
            >
                <Box sx={{ display: "flex", gap: 2 }}>
                    {statusOrder.map((status) => (
                        <DroppableContainer key={status} id={status}>
                            {renderOrders(status)}
                        </DroppableContainer>
                    ))}
                </Box>
            </DndContext>

            <Dialog open={!!selectedOrder} onClose={() => setSelectedOrder(null)}>
                <DialogTitle>Order Details</DialogTitle>
                <DialogContent sx={{ bgcolor: theme.palette.background.paper }}>
                    {selectedOrder && (
                        <Box sx={{ color: theme.palette.text.primary }}>
                            <Typography variant="body1">
                                <strong>Order ID:</strong> {selectedOrder.id}
                            </Typography>
                            <Typography variant="body1">
                                <strong>Date:</strong> {selectedOrder.date}
                            </Typography>
                            <Typography variant="body1">
                                <strong>Address:</strong> {selectedOrder.address}
                            </Typography>
                            <Typography variant="body1" sx={{ mt: 2 }}>
                                <strong>Items:</strong>
                            </Typography>
                            {selectedOrder.items.map((item, idx) => (
                                <Typography key={idx} variant="body2">
                                    {item.quantity}x {item.name} – {item.price.toFixed(2)} €
                                </Typography>
                            ))}
                            <Typography variant="body1" sx={{ mt: 2 }}>
                                <strong>Total:</strong> {selectedOrder.total.toFixed(2)} €
                            </Typography>
                            <Button
                                variant="contained"
                                color="primary"
                                sx={{ mt: 2 }}
                                onClick={() => {
                                    handleNextStatus(selectedOrder);
                                    setSelectedOrder(null);
                                }}
                            >
                                Move to Next Status
                            </Button>
                        </Box>
                    )}
                </DialogContent>
            </Dialog>
        </Box>
    );
}
