import {
  ActionIcon,
  Box,
  Card,
  Group,
  Menu,
  Modal,
  ModalProps,
  ScrollArea,
  Text,
  Title,
} from "@mantine/core";
import {
  IconDots,
  IconPlayerRecordFilled,
  IconTrash,
  IconVideoFilled,
} from "@tabler/icons-react";
import moment from "moment";
import { useEffect, useState } from "react";
import ReactPlayer from "react-player";
import { deleteRecord, getRecords } from "../../apis/bid";
import { useConfirmStore } from "../../lib/zustand/use-confirm";
import { IBid } from "../../system/type";

export interface IRecordModalProps extends ModalProps {
  data: IBid | null;
  onUpdated?: () => void;
}

interface IRecord {
  bid_id: number;
  name: string;
  original_name: string;
  timestamp: number;
}

export default function RecordModal({ data, ...props }: IRecordModalProps) {
  const [records, setRecords] = useState<IRecord[]>([]);
  const [selected, setSelected] = useState<IRecord | null>(null);

  const { setConfirm } = useConfirmStore();

  const fetch = async () => {
    if (!data) return;
    const response = await getRecords(data);
    if (response?.data) {
      setRecords(response.data);
      setSelected(response.data[0]);
    }
  };

  const handleDelete = async (item: IRecord) => {
    setConfirm({
      handleOk: async () => {
        const result = await deleteRecord(item.original_name);

        if (!result?.data) return;

        fetch();
      },
    });
  };

  useEffect(() => {
    fetch();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

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

                      {selected &&
                        selected.original_name === item.original_name && (
                          <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(item)}
                          leftSection={<IconTrash size={14} />}
                          color="red"
                        >
                          Delete
                        </Menu.Item>
                      </Menu.Dropdown>
                    </Menu>
                  </Group>
                </Card.Section>
                <Text mt={"xs"} size="sm" fw={500}>
                  {item.name}
                </Text>

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

        {/* Player - Main content */}
        {records.length > 0 && (
          <Box className="md:col-span-2">
            {selected && (
              <ReactPlayer
                url={`${import.meta.env.VITE_BASE_URL}bids/record/${
                  selected.original_name
                }`}
                controls
                width="100%"
                height="auto"
              />
            )}
          </Box>
        )}

        {records.length <= 0 && (
          <Box className="col-span-3">
            <Text className="text-center" c="dimmed">
              No video
            </Text>
          </Box>
        )}
      </Box>
    </Modal>
  );
}
