import { useEffect, useMemo, useState } from "react";
import {
  Modal,
  Box,
  Text,
  Flex,
  Button,
  ScrollArea,
  Checkbox,
} from "@mantine/core";
import type { TLine, TStation } from "../../untils/types";
import type { Socket } from "socket.io-client";

interface Props {
  listLines: TLine[];
  setListLines: (lines: React.SetStateAction<TLine[]>) => void;
  socket: Socket | null;
  station: TStation | undefined;
}

interface PropsLines {
  id: number | undefined;
  checked: boolean;
  pid?: string;
  sn?: string;
  vid?: string;
  lineNumber?: number;
}

export default function ModalConfirmRunPhysical({
  listLines,
  setListLines,
  socket,
  station,
}: Props) {
  const user = useMemo(() => {
    return localStorage.getItem("user") &&
      typeof localStorage.getItem("user") === "string"
      ? JSON.parse(localStorage.getItem("user") || "")
      : null;
  }, []);
  const [dataLines, setDataLines] = useState<PropsLines[]>([]);
  const [isDisabled, setIsDisabled] = useState<boolean>(false);

  useEffect(() => {
    if (listLines) {
      setDataLines(() =>
        listLines
          .filter((line) => line.id)
          .map((line) => ({
            id: line.id,
            lineNumber: line?.lineNumber,
            pid: line?.inventory?.pid,
            sn: line?.inventory?.sn,
            vid: line?.inventory?.vid,
            checked: true,
          })),
      );
    }
  }, [listLines]);

  return (
    <Modal
      size={"xl"}
      style={{ position: "absolute", left: 0 }}
      opened={dataLines.length > 0}
      onClose={() => {
        setListLines([]);
        setDataLines([]);
      }}
      closeOnClickOutside={false}
      closeOnEscape={false}
      centered
      title="Confirm Run Test Ports"
    >
      <Box>
        <ScrollArea h={"30vh"}>
          {dataLines.map((line, i) => (
            <Box
              key={i}
              style={{
                border: "1px #ccc solid",
                borderTop:
                  i < dataLines.length - 1 || dataLines.length <= 2
                    ? "1px solid #ccc"
                    : 0,
                borderBottom:
                  i !== 0 || dataLines.length === 1 ? "1px solid #ccc" : 0,
              }}
            >
              <Flex
                p={"xs"}
                align={"center"}
                style={{
                  fontWeight: 600,
                }}
                gap={"lg"}
              >
                <Checkbox
                  checked={line.checked}
                  onChange={(e) =>
                    setDataLines(
                      dataLines.map((el) =>
                        el.id === line.id
                          ? {
                              ...el,
                              checked: e.target.checked,
                            }
                          : el,
                      ),
                    )
                  }
                />
                <Text size="lg" fw={600}>
                  Line: {line.lineNumber}
                </Text>
                <Text size="lg" fw={600}>
                  PID: {line.pid || ""}
                </Text>
                <Text size="lg" fw={600}>
                  SN: {line.sn || ""}
                </Text>
                <Text size="lg" fw={600}>
                  VID: {line.vid || ""}
                </Text>
              </Flex>
            </Box>
          ))}
          <Flex justify={"end"} mt={"xs"}>
            <Button
              disabled={
                isDisabled || dataLines.filter((el) => el.checked).length === 0
              }
              color={"green"}
              onClick={() => {
                const listChecked = dataLines.filter((el) => el.checked);
                const listNotChecked = dataLines.filter((el) => !el.checked);
                listChecked.forEach((line) => {
                  socket?.emit("run_physical_test", {
                    lineId: line?.id,
                    stationId: Number(station?.id),
                    userName: user?.firstName
                      ? `${user.firstName} ${user.lastName || ""}`
                      : user?.userName || "Unknown User",
                  });
                });
                setDataLines(listNotChecked);
                setListLines(
                  listLines.filter((el) =>
                    listNotChecked.find((li) => li.id === el.id),
                  ),
                );
                setIsDisabled(true);
                setTimeout(() => {
                  setIsDisabled(false);
                }, 1000);
              }}
            >
              Run
            </Button>
          </Flex>
        </ScrollArea>
      </Box>
    </Modal>
  );
}
