import {
  FieldDataType,
  I18N_T,
  ModelsFieldsTypeMap,
  ModelType,
  convertPrismaDecimal,
} from '@gadmin2n/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';
import { agentAttrs } from '../components/agentPanel/agentAttributes';

const { 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, index: number) => (
          <TextField key={index} 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
              key={v}
              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
            key={v}
            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)) {
    const displayValue = convertPrismaDecimal(value);
    if (
      displayValue !== undefined &&
      displayValue !== null &&
      !isNaN(Number(displayValue))
    ) {
      element = <NumberField value={displayValue ?? ''} />;
    }
  } else if (fieldType === 'JSON') {
    if (value === null || value === undefined) {
      element = <Text type="secondary">-</Text>;
    } else {
      const text =
        typeof value === 'string' ? value : JSON.stringify(value, null, 2);
      element = (
        <Text
          code
          style={{
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
            display: 'block',
            width: '100%',
          }}
        >
          {text}
        </Text>
      );
    }
  } else if (
    typeof value === 'object' &&
    value !== null &&
    !React.isValidElement(value)
  ) {
    // 兜底：未识别 fieldType 但 value 是普通对象，stringify 避免渲染崩溃
    element = (
      <Text
        code
        style={{
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word',
          display: 'block',
          width: '100%',
        }}
      >
        {JSON.stringify(value, null, 2)}
      </Text>
    );
  }
  return (
    <div
      key={fieldName}
      style={{
        display: 'flex',
        borderBottom: '1px solid #f0f0f0',
        minHeight: 48,
      }}
      {...agentAttrs({
        type: 'show-field',
        field: fieldName,
        resource: resourceName,
        meta: { fieldType },
      })}
    >
      <div
        style={{
          width: 180,
          minWidth: 180,
          padding: '10px 16px',
          background: '#fafafa',
          borderRight: '1px solid #f0f0f0',
          fontWeight: 500,
          fontSize: 13,
          color: '#595959',
          display: 'flex',
          alignItems: 'center',
          flexShrink: 0,
        }}
      >
        {t(
          `resources.${resourceName}.fields.${fieldName}`,
          fieldName.startsWith('_count.')
            ? 'Count ' +
                t(
                  `resources.${model[fieldName.split('.')[1]]?.type?.toLowerCase() || ''}.name`,
                  fieldName,
                )
            : fieldName,
        )}
      </div>
      <div
        style={{
          flex: 1,
          padding: '10px 16px',
          fontSize: 13,
          color: '#1a1a1a',
          display: 'flex',
          alignItems: 'center',
          wordBreak: 'break-word',
        }}
      >
        {element}
      </div>
    </div>
  );
}
