import React, { useState, useEffect, useImperativeHandle, forwardRef } from 'react';
import { Modal, Table, Button, Image, message, Space } from 'antd';
import { DeleteOutlined, ZoomInOutlined } 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';

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 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');
    setQueryParams({ pageNo: 1, pageSize: 10 });
    setTotal(0);
    setSelectedRowKeys([]);
    await getFaceOrFingerList();
  };

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

  // 获取指纹或人脸列表
  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,
      });
      setTableData(response.list || []);
      setTotal(response.total || 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]);

  // 删除指纹或人脸
  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: t('common.serialNumber'),
      width: 80,
      align: 'center',
      render: (_: any, __: UserCharacteristic, index: number) => {
        return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
      },
    },
    {
      title: dataType === 'finger' ? t('form.fingerprint') : t('form.face'),
      align: 'center',
      render: (_: any, record: UserCharacteristic) => (
        <div style={{ position: 'relative', display: 'inline-block' }}>
          <Image
            width={60}
            height={60}
            src={record.imageUrl}
            alt={dataType === 'finger' ? t('form.fingerprint') : t('form.face')}
            preview={{
              mask: <ZoomInOutlined />,
            }}
            style={{ borderRadius: 4, border: '1px solid #dcdfe6' }}
          />
        </div>
      ),
    },
    {
      title: t('table.createTime'),
      align: 'center',
      width: 180,
      render: (_: any, record: UserCharacteristic) => formatDateTimeFull(record.createTime),
    },
    {
      title: t('table.operation'),
      align: 'center',
      width: 120,
      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' }}>
        <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={{ y: 450 }}
        bordered
      />

      {/* 分页 */}
      {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;
