import React, { useState, useEffect } from 'react';
import { Search, Plus, RefreshCw, Edit2, Trash2 } from 'lucide-react';
import { keyApi, KeyVO, PageParam } from '../api/Key';
import { toast } from 'sonner';
import { Modal, Button, Input, Space, Table, Form, Switch, Radio, Tooltip } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { DICT_TYPE, getStrDictOptions } from '../utils/dict';
import { dateFormatter } from '../utils/formatTime';
import { Button as UIButton } from './ui/button';
import { useTranslation } from 'react-i18next';
import PermissionWrapper from './PermissionWrapper';
import './IsolationWorkListTable.css';

interface KeyManagementProps {
  subMenu?: string;
}

export default function KeyManagement({ subMenu }: KeyManagementProps) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(true);
  const [list, setList] = useState<KeyVO[]>([]);
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [queryParams, setQueryParams] = useState<PageParam>({
    pageNo: 1,
    pageSize: 10,
    keyName: undefined,
  });
  const [showKeyForm, setShowKeyForm] = useState(false);
  const [editingKey, setEditingKey] = useState<KeyVO | null>(null);

  // 获取钥匙列表
  const getList = async (params?: PageParam) => {
    const currentParams = params || queryParams;
    setLoading(true);
    try {
      const response = await keyApi.listKey(currentParams);
      setList(response.list || []);
      setTotal(response.total || 0);
    } catch (error: any) {
      toast.error(error.message || t('keyManagement.getKeyListFailed'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getList();
  }, [queryParams.pageNo, queryParams.pageSize, queryParams.keyName]);

  // 搜索钥匙
  const handleQuery = () => {
    const newParams = { ...queryParams, pageNo: 1 };
    setQueryParams(newParams);
    getList(newParams);
  };

  // 重置搜索
  const resetQuery = () => {
    const resetParams: PageParam = {
      pageNo: 1,
      pageSize: 10,
      keyName: undefined,
    };
    setQueryParams(resetParams);
    getList(resetParams);
  };

  // 删除钥匙
  const handleDelete = async (id?: number) => {
    const ids = id ? [id] : selectedRowKeys.map(key => Number(key));
    if (ids.length === 0) {
      toast.error(t('common.pleaseSelect'));
      return;
    }

    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('common.confirmDeleteText')} {ids.length} {t('common.items')}?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDelete'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await keyApi.delKey(ids);
          toast.success(t('common.deleteSuccess'));
          setSelectedRowKeys([]);
          await getList();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 打开钥匙表单
  const openKeyForm = (type: 'create' | 'update', id?: number) => {
    if (type === 'create') {
      setEditingKey(null);
      setShowKeyForm(true);
    } else if (type === 'update' && id) {
      keyApi.getKeyInfo(id).then((data) => {
        setEditingKey(data);
        setShowKeyForm(true);
      }).catch((error: any) => {
        toast.error(error.message || t('keyManagement.getKeyInfoFailed'));
      });
    }
  };

  // 保存钥匙
  const saveKey = async (formData: KeyVO) => {
    try {
      if (formData.keyId || formData.id) {
        await keyApi.updateKey({
          ...formData,
          keyId: formData.keyId || formData.id,
        });
        toast.success(t('common.updateSuccess'));
      } else {
        await keyApi.addKey(formData);
        toast.success(t('common.addSuccess'));
      }
      setShowKeyForm(false);
      setEditingKey(null);
      await getList();
    } catch (error: any) {
      toast.error(error.message || t('common.saveFailed'));
    }
  };

  // 钥匙列表表格列
  const keyColumns: ColumnsType<KeyVO> = [
    {
      title: t('table.keyName'),
      dataIndex: 'keyName',
      width: 160,
    },
    {
      title: t('table.keyNfc'),
      dataIndex: 'keyNfc',
      width: 160,
      ellipsis: true,
    },
    {
      title: t('table.keySpec'),
      dataIndex: 'keySpec',
      width: 160,
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: t('table.macAddress'),
      dataIndex: 'macAddress',
      width: 160,
      render: (text: string) => text || '-',
    },
    {
      title: t('table.status'),
      dataIndex: 'exStatus',
      width: 100,
      align: 'center',
      render: (status: string) => {
        if (status === null || status === undefined) return '-';
        const isEnabled = status === '1';
        return (
          <span className={`inline-flex px-3 py-1 rounded-lg text-xs ${
            isEnabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-700'
          }`}>
            {isEnabled ? t('common.enabled') : t('common.disabled')}
          </span>
        );
      },
    },
    {
      title: t('table.remark'),
      dataIndex: 'exRemark',
      width: 220,
      ellipsis: true,
      render: (text: string) => {
        const remarkText = text || '-';
        const maxLength = 20;
        const shouldTruncate = remarkText.length > maxLength;
        const displayText = shouldTruncate ? remarkText.slice(0, maxLength) + '...' : remarkText;
        
        return (
          <Tooltip placement="topLeft" title={remarkText}>
            <span>{displayText}</span>
          </Tooltip>
        );
      },
    },
    {
      title: t('table.createTime'),
      dataIndex: 'createTime',
      width: 180,
      render: (text: string | Date) => text ? dateFormatter(text) : '-',
    },
    {
      title: t('table.operation'),
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_: any, record: KeyVO) => (
        <div className="flex items-center gap-2 justify-center">
          <PermissionWrapper permission="iscs:key:update">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => openKeyForm('update', record.keyId || record.id)}
              className="h-8 px-2 transition-colors hover:underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#000000';
                e.currentTarget.style.textDecoration = 'none';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
              }}
            >
              <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.edit')}</span>
            </UIButton>
          </PermissionWrapper>
          <PermissionWrapper permission="iscs:key:delete">
            <UIButton
              variant="ghost"
              size="sm"
              onClick={() => handleDelete(record.keyId || record.id)}
              className="h-8 px-2 transition-colors hover:underline"
              style={{ color: '#000000' }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#1677ff';
                e.currentTarget.style.textDecoration = 'underline';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#000000';
                e.currentTarget.style.textDecoration = 'none';
                e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
              }}
            >
              <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
              <span className="ml-1">{t('common.delete')}</span>
            </UIButton>
          </PermissionWrapper>
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      {/* 钥匙列表 - 搜索栏和表格放在一起 */}
      <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm overflow-hidden">
        {/* 搜索栏 */}
        <div className="p-4 lg:p-5 border-b border-gray-200">
          <div className="flex items-center justify-between gap-3 lg:gap-4 flex-wrap min-w-0">
            {/* 搜索条件：按原宽度 200px，不超出，可缩小 */}
            <div className="flex items-center gap-2 lg:gap-3 flex-wrap min-w-0">
              <div className="flex items-center gap-2 lg:gap-3 w-[200px] min-w-[100px] flex-shrink">
                <label className="text-sm font-medium text-gray-700 whitespace-nowrap flex-shrink-0">{t('form.keyName')}：</label>
                <Input
                  value={queryParams.keyName || ''}
                  onChange={(e) => setQueryParams({ ...queryParams, keyName: e.target.value })}
                  onPressEnter={handleQuery}
                  placeholder={t('form.keyNamePlaceholder')}
                  className="min-w-0 w-full"
                  allowClear
                />
              </div>
              <Space className="flex-shrink-0" size="small">
                <PermissionWrapper permission="iscs:key:query">
                  <Button
                    type="primary"
                    icon={<Search className="w-4 h-4" />}
                    onClick={handleQuery}
                  >
                    {t('common.search')}
                  </Button>
                </PermissionWrapper>
                
                <PermissionWrapper permission="iscs:key:query">
                  <Button
                    icon={<RefreshCw className="w-4 h-4" />}
                    onClick={resetQuery}
                  >
                    {t('common.reset')}
                  </Button>
                </PermissionWrapper>
              </Space>
            </div>

            {/* 新增 / 批量删除等按钮组保持在最右侧 */}
            <Space className="flex-shrink-0" size="small">
              <PermissionWrapper permission="iscs:key:create">
                <Button
                  type="primary"
                  icon={<Plus className="w-4 h-4" />}
                  onClick={() => openKeyForm('create')}
                >
                  {t('common.addNew')}
                </Button>
              </PermissionWrapper>
              
              <PermissionWrapper permission="iscs:key:delete">
                <Button
                  danger
                  icon={<Trash2 className="w-4 h-4" />}
                  onClick={() => handleDelete()}
                  disabled={selectedRowKeys.length === 0}
                >
                  {t('keyManagement.batchDelete')}
                </Button>
              </PermissionWrapper>
            </Space>
          </div>
        </div>

        {/* 表格 */}
        <div className="isolation-work-list-table min-w-0">
          <Table
            columns={keyColumns}
            dataSource={list}
            rowKey={(record) => record.keyId || record.id || ''}
            loading={loading}
            pagination={false}
            scroll={{ x: 'max-content' }}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelectedRowKeys,
            }}
            rowClassName={(_, index) =>
              index !== undefined && index % 2 === 1 ? 'isolation-work-list-row-alt' : ''
            }
          />
        </div>
      </div>

      {/* 分页 */}
      {!loading && list.length > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! - 1 })}
                disabled={queryParams.pageNo! <= 1}
              >
                {t('common.prevPage')}
              </Button>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize!) || 1}
              </span>
              <Button
                onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo! + 1 })}
                disabled={queryParams.pageNo! >= Math.ceil(total / queryParams.pageSize!)}
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 钥匙表单弹窗 */}
      {showKeyForm && (
        <KeyFormModal
          visible={showKeyForm}
          editingKey={editingKey}
          onCancel={() => {
            setShowKeyForm(false);
            setEditingKey(null);
          }}
          onSave={saveKey}
        />
      )}
    </div>
  );
}

// 钥匙表单弹窗组件
interface KeyFormModalProps {
  visible: boolean;
  editingKey: KeyVO | null;
  onCancel: () => void;
  onSave: (data: KeyVO) => void;
}

function KeyFormModal({ visible, editingKey, onCancel, onSave }: KeyFormModalProps) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [formLoading, setFormLoading] = useState(false);
  const [statusOptions] = useState(() => {
    return getStrDictOptions(DICT_TYPE.KEY_STATUS);
  });

  useEffect(() => {
    if (visible) {
      if (editingKey) {
        form.setFieldsValue({
          hardwareId: editingKey.hardwareId,
          keyName: editingKey.keyName || '',
          keyNfc: editingKey.keyNfc || '',
          macAddress: editingKey.macAddress || '',
          keySpec: editingKey.keySpec || '',
          exStatus: editingKey.exStatus || '1',
          exRemark: editingKey.exRemark || '',
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          hardwareId: undefined,
          keyName: '',
          keyNfc: '',
          macAddress: '',
          keySpec: '',
          exStatus: '1',
          exRemark: '',
        });
      }
    } else {
      // 弹窗关闭时重置表单
      form.resetFields();
    }
  }, [visible, editingKey, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const submitData: KeyVO = {
        ...values,
      };
      
      // 如果是编辑模式，添加 keyId
      if (editingKey) {
        submitData.keyId = editingKey.keyId || editingKey.id;
        submitData.id = editingKey.keyId || editingKey.id;
      }
      
      onSave(submitData);
    } catch (error) {
      // 表单验证失败
    } finally {
      setFormLoading(false);
    }
  };

  return (
    <Modal
      title={editingKey ? t('form.editKey') : t('form.addKey')}
      open={visible}
      onOk={handleSubmit}
      onCancel={onCancel}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      confirmLoading={formLoading}
      width={600}
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        className="mt-4"
      >
        <Form.Item
          label={t('form.keyName')}
          name="keyName"
          rules={[{ required: true, message: t('form.keyNameRequired') }]}
        >
          <Input placeholder={t('form.keyNamePlaceholder')} />
        </Form.Item>
        
        <Form.Item
          label={t('form.keyNfc')}
          name="keyNfc"
          rules={[{ required: true, message: t('form.keyNfcRequired') }]}
        >
          <Input 
            placeholder={t('form.keyNfcPlaceholder')} 
            maxLength={16}
          />
        </Form.Item>
        
        <Form.Item
          label={t('form.macAddress')}
          name="macAddress"
          rules={[{ required: true, message: t('form.macAddressRequired') }]}
        >
          <Input placeholder={t('form.macAddressPlaceholder')} />
        </Form.Item>
        
        <Form.Item
          label={t('form.keySpec')}
          name="keySpec"
        >
          <Input placeholder={t('form.keySpecPlaceholder')} />
        </Form.Item>
        
        <Form.Item
          label={t('form.status')}
          name="exStatus"
        >
          <Radio.Group>
            {statusOptions.map(option => (
              <Radio key={option.value} value={option.value}>
                {option.label}
              </Radio>
            ))}
          </Radio.Group>
        </Form.Item>
        
        <Form.Item
          label={t('form.remark')}
          name="exRemark"
        >
          <Input.TextArea placeholder={t('form.remarkPlaceholder')} rows={3} />
        </Form.Item>
      </Form>
    </Modal>
  );
}

