/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  ActionIcon,
  Box,
  Card,
  Group,
  Menu,
  Modal,
  ModalProps,
  ScrollArea,
  Text,
  Title,
} from "@mantine/core";
import {
  IconCodeCircle,
  IconDots,
  IconPlayerRecordFilled,
  IconTrash,
} from "@tabler/icons-react";
import moment from "moment";
import { useEffect, useRef, useState } from "react";
import ReactJson from "react-json-view";
import { updateMetadata } from "../../apis/bid";
import { useConfirmStore } from "../../lib/zustand/use-confirm";
import { IBid, IMetadata } from "../../system/type";
import { getResponseDemo } from "../../utils";
export interface IResponseDemoProps extends ModalProps {
  data: IBid | null;
  onUpdated?: () => void;
}

export default function ResponseDemoModal({
  data,
  ...props
}: IResponseDemoProps) {
  const { setConfirm } = useConfirmStore();
  const [selected, setSelected] = useState<Record<string, any> | null>(null);

  const [responseDemo, setResponseDemo] = useState<null | IMetadata>(null);

  const dataRef = useRef<IBid | null>(data);
  // const responseDemo = useMemo(() => {
  //   if (!data) return null;

  //   const values = getResponseDemo(data);

  //   if (Array.isArray(values?.value) && values?.value[0]) {
  //     setSelected(values?.value[0]);
  //   }

  //   return values;
  // }, [data]);

  useEffect(() => {
    if (!data) return;

    const value = getResponseDemo(data);

    if (Array.isArray(value?.value) && value?.value[0]) {
      setSelected(value?.value[0]);
    }

    setResponseDemo(value);
    dataRef.current = data;
  }, [data]);

  const handleDelete = async () => {
    if (!responseDemo || !selected) return;
    console.log(selected);
    setConfirm({
      handleOk: async () => {
        const prevData = responseDemo.value as Record<string, any>[];

        const newData = prevData.filter(
          (item) => item?.uuid !== selected?.uuid
        );

        const result = await updateMetadata(
          responseDemo.id,
          JSON.stringify(newData)
        );

        if (!result?.data) return;

        props.onUpdated?.();

        setResponseDemo(result.data);
        if (result?.data?.value[0]) {
          setSelected(result?.data?.value[0]);
        } else {
          setSelected(null);
        }
        // props.onClose();
      },
    });
  };

  return (
    <Modal
      classNames={{
        header: "!flex !justify-center w-full",
      }}
      {...props}
      size={"xl"}
      title={<Title order={3}>Response Demo</Title>}
      centered
    >
      <Box className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* Sidebar - Record list */}
        {responseDemo && responseDemo?.value.length > 0 && (
          <ScrollArea className="md:col-span-1 h-[600px] pr-2">
            {Array.isArray(responseDemo.value) &&
              responseDemo.value.map((item) => {
                return (
                  <Card
                    onClick={() => setSelected(item)}
                    key={item.uuid}
                    withBorder
                    shadow="xs"
                    radius="md"
                    className={`mb-3 cursor-pointer transition-all ${"border-blue-500 bg-blue-50"}`}
                  >
                    <Card.Section withBorder inheritPadding py="xs">
                      <Group justify="space-between">
                        <Group>
                          <IconCodeCircle />

                          {selected && selected?.uuid === item?.uuid && (
                            <IconPlayerRecordFilled
                              size={14}
                              color="red"
                              className="animate-pulse"
                            />
                          )}
                        </Group>

                        <Menu withinPortal position="bottom-end" shadow="sm">
                          <Menu.Target>
                            <ActionIcon variant="subtle" color="gray">
                              <IconDots size={16} />
                            </ActionIcon>
                          </Menu.Target>

                          <Menu.Dropdown>
                            <Menu.Item
                              onClick={handleDelete}
                              leftSection={<IconTrash size={14} />}
                              color="red"
                            >
                              Delete
                            </Menu.Item>
                          </Menu.Dropdown>
                        </Menu>
                      </Group>
                    </Card.Section>
                    <Text mt={"xs"} size="sm" fw={500}>
                      {dataRef.current?.name}
                    </Text>

                    <Text mt="xs" c="dimmed" size="xs">
                      {item?.timestamp &&
                        moment(Number(item?.timestamp)).fromNow()}
                    </Text>
                  </Card>
                );
              })}
          </ScrollArea>
        )}

        {/* Player - Main content */}
        {responseDemo?.value && selected && (
          <ScrollArea h={600} className="md:col-span-2">
            <ReactJson theme={"bespin"} src={selected || {}} />
          </ScrollArea>
        )}

        {(!responseDemo ||
          (Array.isArray(responseDemo.value) &&
            responseDemo.value.length <= 0)) && (
          <Box className="col-span-3">
            <Text className="text-center" c="dimmed">
              No response
            </Text>
          </Box>
        )}
      </Box>
    </Modal>
  );
}
