import PhotoActionModal from '@/components/shared/PhotoActionModal';
import { DEFAULT_PAGE_SIZE, HTTPSTATUS } from '@/constants';
import {
  apiDeleteFishSpecies,
  apiGetFishSpecies,
} from '@/services/slave/sgw/FishController';
import { getRarityById } from '@/utils/slave/sgw/fishRarity';
import {
  DeleteOutlined,
  EditOutlined,
  PictureOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Flex, message, Popconfirm, Tag, theme, Tooltip } from 'antd';
import { useRef, useState } from 'react';
import AddOrUpdateFish from './component/AddOrUpdateFish';
import { FishImage } from './component/FishImage';

const FishList = () => {
  const tableRef = useRef<ActionType>();
  const intl = useIntl();
  const [messageApi, contextHolder] = message.useMessage();
  const [showAddOrUpdateModal, setShowAddOrUpdateModal] =
    useState<boolean>(false);
  const [fishSelected, setFishSelected] = useState<SgwModel.Fish | undefined>(
    undefined,
  );
  const [fishPhotoModalOpen, setFishPhotoModalOpen] = useState<boolean>(false);
  const [fishID, setFishID] = useState<number | undefined>(undefined);
  const [isReloadImage, setIsReloadImage] = useState<boolean>(false);
  const token = theme.useToken();
  const getColorByRarityLevel = (level: number) => {
    switch (level) {
      case 2:
        return token.token.yellow;
      case 3:
        return token.token.orange;
      case 4:
        return token.token.colorError;
      case 5:
        return '#FF6347';
      case 6:
        return '#FF4500';
      case 7:
        return '#FF0000';
      case 8:
        return '#8B0000';
      default:
        return token.token.green;
    }
  };

  const handleDeleteFish = async (id: string) => {
    try {
      const resp = await apiDeleteFishSpecies(id);
      if (resp.status === HTTPSTATUS.HTTP_SUCCESS) {
        messageApi.success(
          intl.formatMessage({
            id: 'fish.delete.success',
            defaultMessage: 'Successfully deleted fish',
          }),
        );
        tableRef.current?.reload();
      } else {
        throw new Error('Xóa cá thất bại');
      }
    } catch (error) {
      messageApi.error(
        intl.formatMessage({
          id: 'fish.delete.fail',
          defaultMessage: 'Failed to delete fish',
        }),
      );
    }
  };

  const columns: ProColumns<SgwModel.Fish>[] = [
    {
      title: intl.formatMessage({
        id: 'common.name',
        defaultMessage: 'Name',
      }),
      dataIndex: 'name',
      key: 'name',
      copyable: true,
      render: (dom, entity) => {
        return (
          <Tooltip
            title={
              intl.formatMessage({
                id: 'fish.specific_name',
                defaultMessage: 'Scientific Name',
              }) +
              ': ' +
              entity.scientific_name
            }
          >
            {dom}
          </Tooltip>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'common.image',
        defaultMessage: 'Image',
      }),
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
      // valueType: 'image',
      render: (_, entity) => {
        return (
          <FishImage
            fishId={String(entity.id || '')}
            alt={entity.name || ''}
            isReload={isReloadImage}
          />
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'fish.fish_group',
        defaultMessage: 'Group',
      }),
      dataIndex: 'group_name',
      key: 'group_name',
    },
    {
      title: intl.formatMessage({
        id: 'fish.rarity',
        defaultMessage: 'Rarity',
      }),
      dataIndex: 'rarity_level',
      key: 'rarity_level',
      valueType: 'select',
      valueEnum: {
        1: {
          text: intl.formatMessage({
            id: 'fish.rarity.normal',
            defaultMessage: 'Common',
          }),
        },
        2: {
          text: intl.formatMessage({
            id: 'fish.rarity.sensitive',
            defaultMessage: 'Sensitive',
          }),
        },
        3: {
          text: intl.formatMessage({
            id: 'fish.rarity.near_threatened',
            defaultMessage: 'Near Threatened',
          }),
        },
        4: {
          text: intl.formatMessage({
            id: 'fish.rarity.endangered',
            defaultMessage: 'Endangered',
          }),
        },
      },
      render: (_, entity) => {
        const rarity = getRarityById(entity.rarity_level || 1);
        return (
          <Tag color={getColorByRarityLevel(entity.rarity_level || 1)}>
            {rarity ||
              intl.formatMessage({
                id: 'common.undefined',
                defaultMessage: 'Undefined',
              })}
          </Tag>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'common.note',
        defaultMessage: 'Note',
      }),
      dataIndex: 'note',
      hideInSearch: true,
      key: 'note',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({
        id: 'common.actions',
        defaultMessage: 'Actions',
      }),
      dataIndex: 'actions',
      key: 'actions',
      hideInSearch: true,
      align: 'center',
      render: (_, entity) => {
        return (
          <Flex align="center" justify="center" gap={8}>
            <Button
              type="text"
              onClick={() => {
                setFishSelected(entity);
                setShowAddOrUpdateModal(true);
              }}
              icon={<EditOutlined />}
            ></Button>
            <Button
              type="text"
              onClick={async () => {
                setFishID(entity.id);
                setFishPhotoModalOpen(true);
              }}
              icon={<PictureOutlined />}
            ></Button>
            <Popconfirm
              title={intl.formatMessage({
                id: 'fish.delete_confirm',
                defaultMessage:
                  'Are you sure you want to delete this fish species?',
              })}
              onConfirm={() => handleDeleteFish(entity.id?.toString() || '')}
              okText={intl.formatMessage({
                id: 'common.yes',
                defaultMessage: 'Yes',
              })}
              cancelText={intl.formatMessage({
                id: 'common.no',
                defaultMessage: 'No',
              })}
            >
              <Button type="text" danger icon={<DeleteOutlined />}></Button>
            </Popconfirm>
          </Flex>
        );
      },
    },
  ];

  return (
    <div>
      {contextHolder}
      <AddOrUpdateFish
        type={fishSelected ? 'update' : 'create'}
        isOpen={showAddOrUpdateModal}
        setIsOpen={setShowAddOrUpdateModal}
        fish={fishSelected}
        message={messageApi}
        onReload={(isSuccess) => {
          if (isSuccess) {
            tableRef.current?.reload();
            setIsReloadImage((prev) => !prev);
          }
        }}
      />
      <PhotoActionModal
        key={fishID ?? 'none'}
        isOpen={fishPhotoModalOpen}
        setIsOpen={setFishPhotoModalOpen}
        type={'fish'}
        id={fishID!}
        hasSubPhotos={true}
      />
      <ProTable<SgwModel.Fish>
        actionRef={tableRef}
        rowKey="id"
        size="large"
        columns={columns}
        search={{
          defaultCollapsed: false,
        }}
        columnEmptyText="-"
        pagination={{
          defaultPageSize: DEFAULT_PAGE_SIZE * 2,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '15', '20'],
          showTotal: (total, range) =>
            `${range[0]}-${range[1]} 
                            ${intl.formatMessage({
                              id: 'common.of',
                              defaultMessage: 'of',
                            })}
                          ${total} ${intl.formatMessage({
              id: 'fish.name',
              defaultMessage: 'fishes',
            })}`,
        }}
        options={{
          search: false,
          setting: false,
          density: false,
          reload: true,
        }}
        toolBarRender={() => [
          <Button
            color="cyan"
            variant="outlined"
            key="add-fish"
            icon={<PlusOutlined />}
            size="middle"
            onClick={() => {
              setFishSelected(undefined);
              setShowAddOrUpdateModal(true);
            }}
          >
            <FormattedMessage
              id="fish.create.title"
              defaultMessage="Add Fish Species"
            />
          </Button>,
        ]}
        request={async (params) => {
          const { current, pageSize, name, group_name, rarity_level } = params;
          const offset = current === 1 ? 0 : (current! - 1) * pageSize!;
          const body: SgwModel.SearchFishPaginationBody = {
            name: name,
            order: 'name',
            limit: pageSize,
            offset: offset,
            dir: 'desc',
          };
          if (group_name || rarity_level) body.metadata = {};
          if (group_name && body.metadata) {
            body.metadata.group_name = group_name;
          }
          if (rarity_level && body.metadata) {
            body.metadata.rarity_level = Number(rarity_level);
          }
          try {
            const res = await apiGetFishSpecies(body);
            return {
              data: res.fishes,
              total: res.total,
              success: true,
            };
          } catch (error) {
            return {
              data: [],
              total: 0,
              success: false,
            };
          }
        }}
      />
    </div>
  );
};

export default FishList;
