import {
  FieldDataType,
  I18N_T,
  ModelsFieldsTypeMap,
  ModelType,
} from "@gadmin2/react-common";
import {
  TagField,
  MarkdownField,
  TextField,
  ImageField,
  FileField,
  DateField,
  UrlField,
  EmailField,
  BooleanField,
  NumberField,
  ShowButton,
} from "@refinedev/antd";
import { CheckCircleTwoTone, CloseCircleTwoTone } from "@ant-design/icons";
import { Space, Typography } from "antd";
import React from "react";

const { Title, Text } = Typography;

export function getShowField(
  field: FieldDataType,
  resourceName: string,
  record: any,
  t: I18N_T,
  model: ModelType,
  modelsMap: ModelsFieldsTypeMap
) {
  const { type: fieldType, args } = field.uiType.formItem;
  const fieldName = field.name;
  let value = (record as any)?.[fieldName];
  if (fieldName.includes(".")) {
    const attrs = fieldName.split(".");
    value = (record as any)?.[attrs[0]]?.[attrs[1]];
  }
  let element = <Text>{value}</Text>;
  if (field.render) {
    element = field.render(value);
  } else if (
    !fieldName.includes(".") &&
    field.kind === "object" &&
    !field.isList &&
    value !== undefined &&
    value !== null
  ) {
    const nameKey = modelsMap[model[fieldName].type]?.meta?.nameKeys?.[0];
    element = (
      <ShowButton
        icon={false}
        type="link"
        size="small"
        resource={model[fieldName]?.type?.toLowerCase()}
        recordItemId={value?.id}
      >
        {(record as any)?.[fieldName]?.[nameKey]}
      </ShowButton>
    );
  } else if (fieldType === "Markdown") {
    element = <MarkdownField value={value} />;
  } else if (fieldType === "Text") {
    element = (
      <>
        {(value || "").split("\n").map((row: string) => (
          <TextField style={{ display: "block" }} value={row} />
        ))}
      </>
    );
  } else if (fieldType === "Image") {
    element = (
      <Space wrap>
        {JSON.parse(value || "[]")?.map?.((img: any) => (
          <ImageField
            key={img?.response?.name}
            value={img?.thumbUrl}
            title={img?.name}
            width={200}
          />
        ))}
      </Space>
    );
  } else if (fieldType === "File") {
    element = (
      <Space wrap>
        {JSON.parse(value || "[]")?.map?.((file: any) => (
          <FileField
            key={file?.response?.name}
            src={file?.thumbUrl}
            title={file?.name}
          />
        ))}
      </Space>
    );
  } else if (fieldType === "Select") {
    if (args.mode === "multiple") {
      element = (
        <Space>
          {JSON.parse(value || "[]")?.map?.((v: string) => (
            <TagField
              value={t(`resources.${resourceName}.enums.${fieldName}.${v}`, String(v))}
            />
          ))}
        </Space>
      );
    } else {
      element = <TagField value={t(
        `resources.${resourceName}.enums.${fieldName}.${value}`,
        String(value)
      )} />;
    }
  } else if (fieldType === "Radio" || field.kind === "enum") {
    element = (
      <TagField
        value={t(
          `resources.${resourceName}.enums.${fieldName}.${value}`,
          String(value)
        )}
      />
    );
  } else if (fieldType === "CheckBox") {
    element = (
      <Space>
        {JSON.parse(value || "[]")?.map?.((v: string) => (
          <TagField
            value={t(`resources.${resourceName}.enums.${fieldName}.${v}`, String(v))}
          />
        ))}
      </Space>
    );
  } else if (fieldType === "DateTime") {
    element = <DateField value={value} format="YYYY-MM-DD HH:mm:ss" />;
  } else if (fieldType === "Url") {
    element = <UrlField value={value} />;
  } else if (fieldType === "Email") {
    element = <EmailField value={value} />;
  } else if (fieldType === "Boolean") {
    element = (
      <BooleanField
        value={value}
        trueIcon={<CheckCircleTwoTone twoToneColor="#52c41a" />}
        falseIcon={<CloseCircleTwoTone twoToneColor="red" />}
      />
    );
  } else if (["Int", "BigInt", "Float", "Decimal"].includes(fieldType)) {
    if (value !== undefined && value !== null && !isNaN(value)) {
      element = <NumberField value={value ?? ""} />;
    }
  }
  return (
    <React.Fragment key={fieldName}>
      <Title level={5}>
        {t(
          `resources.${resourceName}.fields.${fieldName}`,
          fieldName.startsWith("_count.")
            ? "Count " +
                t(
                  `resources.${
                    model[fieldName.split(".")[1]]?.type?.toLowerCase() || ""
                  }.name`,
                  fieldName
                )
            : fieldName
        )}
      </Title>
      {element}
    </React.Fragment>
  );
}
