import React, { useState, useEffect, useImperativeHandle, forwardRef, useRef } from 'react';
import { Modal, Table, Button, Image, message, Space, Upload, Input } from 'antd';
import { DeleteOutlined, ZoomInOutlined, PlusOutlined } from '@ant-design/icons';
import { userCharacteristicApi } from '../../api/user/characteristic';
import { UserCharacteristic } from '../../types';
import { formatDateTimeFull } from '../../utils/formatTime';
import type { ColumnsType } from 'antd/es/table';
import { useTranslation } from 'react-i18next';
import axiosInstance from '../../utils/axios';

/** 带鉴权加载的图片：通过 axios 携带 token 请求，解决 img 直链 401 不显示 */
const AuthImage = ({
  src,
  alt,
  width = 60,
  height = 60,
  style,
  noImageText,
}: {
  src: string;
  alt: string;
  width?: number;
  height?: number;
  style?: React.CSSProperties;
  noImageText?: string;
}) => {
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const blobUrlRef = useRef<string | null>(null);

  useEffect(() => {
    if (!src) {
      setLoading(false);
      setError(true);
      return;
    }
    setLoading(true);
    setError(false);
    let cancelled = false;
    axiosInstance
      .get(src, { responseType: 'blob' })
      .then((blob) => {
        if (cancelled) return;
        const url = URL.createObjectURL(blob as Blob);
        blobUrlRef.current = url;
        setBlobUrl(url);
      })
      .catch(() => {
        if (!cancelled) setError(true);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = null;
      }
      setBlobUrl(null);
    };
  }, [src]);

  const placeholderStyle: React.CSSProperties = {
    width,
    height,
    borderRadius: 4,
    border: '1px solid #dcdfe6',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    color: '#999',
    fontSize: 12,
  };

  if (loading) {
    return <div style={placeholderStyle}>...</div>;
  }
  if (error || !blobUrl) {
    return <div style={placeholderStyle}>{noImageText || '暂无图片'}</div>;
  }
  return (
    <Image
      width={width}
      height={height}
      src={blobUrl}
      alt={alt}
      preview={{ mask: <ZoomInOutlined /> }}
      style={{ borderRadius: 4, border: '1px solid #dcdfe6', ...style }}
    />
  );
};

interface FaceOrFingerFormProps {
  onSuccess?: () => void;
}

export interface FaceOrFingerFormRef {
  open: (type: string, id: number, row: any) => void;
}

const FaceOrFingerForm = forwardRef<FaceOrFingerFormRef, FaceOrFingerFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formLoading, setFormLoading] = useState(false);
  const [tableData, setTableData] = useState<UserCharacteristic[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [total, setTotal] = useState(0);
  const [queryParams, setQueryParams] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [userId, setUserId] = useState<number>();
  const [userType, setUserType] = useState<string>();
  const [dataType, setDataType] = useState<'finger' | 'face'>('finger');
  const [currentUserName, setCurrentUserName] = useState('');

  // 新增人脸：上传弹框
  const [uploadVisible, setUploadVisible] = useState(false);
  const [uploadFileList, setUploadFileList] = useState<any[]>([]);
  const [uploadUserName, setUploadUserName] = useState('');
  const [uploadLoading, setUploadLoading] = useState(false);

  // 打开弹窗
  const open = async (type: string, id: number, row: any) => {
    setDialogVisible(true);
    const isFinger = type === 'finger';
    setDataType(isFinger ? 'finger' : 'face');
    setDialogTitle(isFinger ? t('form.fingerprintData') : t('form.faceData'));
    setUserId(row.id);
    setUserType(isFinger ? '1' : '2');
    setCurrentUserName(row?.username ?? row?.nickname ?? '');
    setQueryParams({ pageNo: 1, pageSize: 10 });
    setTotal(0);
    setSelectedRowKeys([]);
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  // 获取指纹或人脸列表（兼容接口返回 { code, data: { list, total }, msg }，axios 会解包为 { list, total }）
  const getFaceOrFingerList = async () => {
    if (!userId || !userType) return;

    setFormLoading(true);
    try {
      const response = await userCharacteristicApi.getUserType({
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
        userId: userId,
        type: userType,
      });
      const list = response?.data?.list ?? response?.list ?? [];
      const totalCount = response?.data?.total ?? response?.total ?? 0;
      setTableData(Array.isArray(list) ? list : []);
      setTotal(typeof totalCount === 'number' ? totalCount : 0);
    } catch (error: any) {
      message.error(error.message || t('form.getDataFailed'));
    } finally {
      setFormLoading(false);
    }
  };

  useEffect(() => {
    if (dialogVisible && userId && userType) {
      getFaceOrFingerList();
    }
  }, [queryParams.pageNo, queryParams.pageSize, dialogVisible, userId, userType]);

  const openUploadModal = () => {
    setUploadFileList([]);
    setUploadUserName(currentUserName);
    setUploadVisible(true);
  };

  const handleUploadSubmit = async () => {
    const userName = uploadUserName?.trim();
    if (!userName) {
      message.warning(t('form.userName') + (t('common.required') ? ` ${t('common.required')}` : '不能为空'));
      return;
    }
    const file = uploadFileList[0]?.originFileObj;
    if (!file) {
      message.warning(t('form.pleaseSelectImage'));
      return;
    }
    setUploadLoading(true);
    try {
      await userCharacteristicApi.insertUserFace(userName, file);
      message.success(t('common.uploadSuccess') || '上传成功');
      setUploadVisible(false);
      setUploadFileList([]);
      await getFaceOrFingerList();
    } catch (error: any) {
      message.error(error?.message || t('common.uploadFailed') || '上传失败');
    } finally {
      setUploadLoading(false);
    }
  };

  // 删除指纹或人脸
  const handleDelete = async (id?: number) => {
    const idsToDelete = id ? [id] : selectedRowKeys.map(key => Number(key));
    
    if (idsToDelete.length === 0) {
      message.warning(t('form.pleaseSelectDataToDelete'));
      return;
    }

    Modal.confirm({
      title: t('common.confirmDelete'),
      content: t('form.confirmDeleteSelectedData', { count: idsToDelete.length }),
      okText: t('common.confirm'),
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          // 逐个删除
          for (const deleteId of idsToDelete) {
            await userCharacteristicApi.deleteUserFaceOrFinger(deleteId);
          }
          message.success(t('common.deleteSuccess'));
          await getFaceOrFingerList();
          setSelectedRowKeys([]);
          onSuccess?.();
        } catch (error: any) {
          message.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 表格列配置
  const columns: ColumnsType<UserCharacteristic> = [
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>{t('common.serialNumber')}</span>,
      width: 130,
      align: 'center',
      render: (_: any, __: UserCharacteristic, index: number) => {
        return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: (
        <span style={{ whiteSpace: 'nowrap' }}>
          {dataType === 'finger' ? t('form.fingerprint') : t('form.face')}
        </span>
      ),
      align: 'center',
      width: 220,
      render: (_: any, record: UserCharacteristic) => {
        const imgSrc = record.imageUrl || record.imagePath;
        return (
          <div style={{ position: 'relative', display: 'inline-block' }}>
            {imgSrc ? (
              <AuthImage
                src={imgSrc}
                alt={dataType === 'finger' ? t('form.fingerprint') : t('form.face')}
                width={60}
                height={60}
                noImageText={t('form.noImage') || '暂无图片'}
              />
            ) : (
              <div style={{ width: 60, height: 60, borderRadius: 4, border: '1px solid #dcdfe6', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999', fontSize: 12 }}>
                {t('form.noImage') || '暂无图片'}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>{t('table.createTime')}</span>,
      align: 'center',
      width: 170,
      render: (_: any, record: UserCharacteristic) => formatDateTimeFull(record.createTime),
    },
    {
      title: <span style={{ whiteSpace: 'nowrap' }}>{t('table.operation')}</span>,
      align: 'center',
      width: 110,
      render: (_: any, record: UserCharacteristic) => (
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id)}
        >
          {t('common.delete')}
        </Button>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys: React.Key[]) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      footer={[
        <Button key="close" onClick={() => setDialogVisible(false)}>
          {t('form.close')}
        </Button>,
      ]}
      width={800}
      destroyOnClose
    >
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        {dataType === 'face' && (
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={openUploadModal}
            disabled={formLoading}
          >
            {t('common.add')}
          </Button>
        )}
        <Button
          type="primary"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete()}
          disabled={selectedRowKeys.length === 0 || formLoading}
        >
          {t('common.delete')}
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={tableData}
        rowKey="id"
        loading={formLoading}
        pagination={false}
        rowSelection={rowSelection}
        scroll={{ x: 'max-content', y: 450 }}
        bordered
      />

      {/* 新增人脸：图片上传弹框（含 userName 输入框，中英文用 form.uploadFace / form.userName / form.selectImage / form.pleaseSelectImage） */}
      <Modal
        title={t('form.uploadFace')}
        open={uploadVisible}
        onCancel={() => { setUploadVisible(false); setUploadFileList([]); }}
        onOk={handleUploadSubmit}
        confirmLoading={uploadLoading}
        okText={t('common.confirm')}
        cancelText={t('common.cancel')}
        destroyOnClose
      >
        <div style={{ marginBottom: 16 }}>
          <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
            {t('form.userName')}
          </label>
          <Input
            value={uploadUserName}
            onChange={(e) => setUploadUserName(e.target.value)}
            placeholder={t('form.userName')}
            allowClear
          />
        </div>
        <div>
          <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
            {t('form.selectImage')}
          </label>
          <Upload
            accept="image/*"
            fileList={uploadFileList}
            listType="picture-card"
            maxCount={1}
            beforeUpload={(file) => {
              setUploadFileList([{ uid: file.uid, name: file.name, status: 'done', originFileObj: file }]);
              return false;
            }}
            onRemove={() => setUploadFileList([])}
          >
            {uploadFileList.length === 0 && t('form.selectImage')}
          </Upload>
        </div>
      </Modal>

      {/* 分页 */}
      {total > 0 && (
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid #f0f0f0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 14, color: '#666' }}>
            {t('common.total')} <span style={{ color: '#1890ff', fontWeight: 500 }}>{total}</span> {t('common.records')}
          </div>
          <Space>
            <Button
              onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
              disabled={queryParams.pageNo <= 1}
            >
              {t('common.prevPage')}
            </Button>
            <span style={{ padding: '0 16px', fontSize: 14, color: '#666' }}>
              {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize)}
            </span>
            <Button
              onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
              disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize)}
            >
              {t('common.nextPage')}
            </Button>
          </Space>
        </div>
      )}
    </Modal>
  );
});

FaceOrFingerForm.displayName = 'FaceOrFingerForm';

export default FaceOrFingerForm;
