import React, { useState, useRef, useEffect } from 'react';
import { Plus, Edit2, Trash2 } from 'lucide-react';
import { dictDataApi, DictDataVO } from '../api/DictData';
import { toast } from 'sonner';
import { formatDateTimeFull } from '../utils/formatTime';
import { getIntDictOptions, DICT_TYPE, getDictLabel, setDictOptions, DictDataType } from '../utils/dict';
import { Modal, Card, Tag, Space, Table, Tooltip } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button } from './ui/button';
import DictDataForm, { DictDataFormRef } from './DictDataForm';
import type { ColumnsType } from 'antd/es/table';
import { useTranslation } from 'react-i18next';

interface DictDataManagementProps {
  dictType: string;
  dictDataList: DictDataVO[];
  onRefresh: () => void;
}

export default function DictDataManagement({ dictType, dictDataList, onRefresh }: DictDataManagementProps) {
  const { t } = useTranslation();
  const [list, setList] = useState<DictDataVO[]>(dictDataList);
  const formRef = useRef<DictDataFormRef>(null);

  // 当 dictDataList 变化时更新 list
  React.useEffect(() => {
    setList(dictDataList);
  }, [dictDataList]);

  // 加载字典管理的状态选项（从接口获取，0=开启，1=关闭）
  const [statusOptions, setStatusOptions] = useState<Array<{ label: string; value: number }>>([]);
  
  useEffect(() => {
    const loadDictStatusOptions = async () => {
      try {
        // 从接口获取 common_status 字典数据
        const response = await dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: 'common_status',
        });
        
        const data = (response as any)?.data || response;
        const dictList = data?.list || [];
        
        if (Array.isArray(dictList) && dictList.length > 0) {
          // 使用接口返回的字典数据
          const options = dictList.map((item: any) => ({
            label: item.label,
            value: typeof item.value === 'string' ? parseInt(item.value, 10) : Number(item.value),
          }));
          setStatusOptions(options);
          console.log('DictDataManagement: 从接口获取状态选项', options);
        } else {
          // 如果接口没有数据，使用字典管理的默认定义：0=开启，1=关闭
          setStatusOptions([
            { label: '开启', value: 0 },
            { label: '关闭', value: 1 },
          ]);
        }
      } catch (error) {
        console.error('加载状态选项失败:', error);
        // 使用字典管理的默认定义：0=开启，1=关闭
        setStatusOptions([
          { label: '开启', value: 0 },
          { label: '关闭', value: 1 },
        ]);
      }
    };

    loadDictStatusOptions();
  }, []);

  // 打开表单
  const openForm = (type: string, id?: number) => {
    if (formRef.current) {
      formRef.current.open(type, id, dictType);
    }
  };

  // 删除字典数据
  const handleDelete = async (id: number, label: string) => {
    Modal.confirm({
      title: t('common.confirmDelete'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('form.deleteDictDataText')} <strong>"{label}"</strong>?</p>
          <p style={{ color: '#ff4d4f', marginTop: '8px' }}>{t('common.confirmDeleteWarning')}</p>
        </div>
      ),
      okText: t('common.confirmDeleteButton'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      onOk: async () => {
        try {
          await dictDataApi.deleteDictData(id);
          toast.success(t('common.deleteSuccess'));
          onRefresh();
        } catch (error: any) {
          toast.error(error.message || t('common.deleteFailed'));
        }
      },
    });
  };

  // 获取状态标签 - 从接口获取的字典数据中查找
  const getStatusLabel = (status: number | string | undefined) => {
    const statusNum = typeof status === 'string' ? parseInt(status, 10) : Number(status);
    // 从接口获取的状态选项中查找
    const statusOption = statusOptions.find(opt => opt.value === statusNum);
    if (statusOption) {
      return statusOption.label;
    }
    // 如果找不到，使用字典管理的默认定义：0=开启，1=关闭
    return statusNum === 0 ? '开启' : '关闭';
  };

  // 获取状态样式 - 字典管理接口：0=开启（绿色），1=关闭（灰色）
  const getStatusStyle = (status: number | string | undefined) => {
    const statusNum = typeof status === 'string' ? parseInt(status, 10) : Number(status);
    // 字典管理接口定义：0=开启（绿色），1=关闭（灰色）
    return statusNum === 0
      ? 'bg-green-100 text-green-700'
      : 'bg-gray-100 text-gray-700';
  };

  // 获取颜色类型标签
  const getColorTypeTag = (colorType: string) => {
    if (!colorType) return null;
    const colorMap: Record<string, string> = {
      'success': 'green',
      'info': 'blue',
      'warning': 'orange',
      'danger': 'red',
      'primary': 'blue',
      'default': 'default',
    };
    return <Tag color={colorMap[colorType] || 'default'}>{colorType}</Tag>;
  };

  const columns: ColumnsType<DictDataVO> = [
    {
      title: t('table.dictCode'),
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      width: 100,
    },
    {
      title: t('table.dictLabel'),
      dataIndex: 'label',
      key: 'label',
      align: 'center',
    },
    {
      title: t('table.dictValue'),
      dataIndex: 'value',
      key: 'value',
      align: 'center',
    },
    {
      title: t('table.dictSort'),
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 100,
    },
    {
      title: t('table.status'),
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 100,
      render: (status: number) => (
        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusStyle(status)}`}>
          {getStatusLabel(status)}
        </span>
      ),
    },
    {
      title: t('table.colorType'),
      dataIndex: 'colorType',
      key: 'colorType',
      align: 'center',
      width: 120,
      render: (colorType: string) => getColorTypeTag(colorType),
    },
    {
      title: 'CSS Class',
      dataIndex: 'cssClass',
      key: 'cssClass',
      align: 'center',
      width: 120,
    },
    {
      title: t('table.remark'),
      dataIndex: 'remark',
      key: 'remark',
      align: 'center',
      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',
      key: 'createTime',
      align: 'center',
      width: 180,
      render: (time: Date) => formatDateTimeFull(time),
    },
    {
      title: t('table.operation'),
      key: 'action',
      align: 'center',
      width: 150,
      fixed: 'right',
      render: (_: any, record: DictDataVO) => (
        <div className="flex items-center gap-2 justify-center">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => openForm('update', record.id)}
            className="h-8 px-2 transition-colors hover:!text-[#1677ff] hover:!underline"
            style={{ color: '#000000' }}
            onMouseEnter={(e) => {
              const target = e.currentTarget as HTMLElement;
              target.style.setProperty('color', '#1677ff', 'important');
              target.style.setProperty('text-decoration', 'underline', 'important');
              const svg = target.querySelector('svg');
              if (svg) {
                svg.style.setProperty('color', '#1677ff', 'important');
              }
              const span = target.querySelector('span');
              if (span) {
                span.style.setProperty('color', '#1677ff', 'important');
              }
            }}
            onMouseLeave={(e) => {
              const target = e.currentTarget as HTMLElement;
              target.style.setProperty('color', '#000000', 'important');
              target.style.setProperty('text-decoration', 'none', 'important');
              const svg = target.querySelector('svg');
              if (svg) {
                svg.style.setProperty('color', '#000000', 'important');
              }
              const span = target.querySelector('span');
              if (span) {
                span.style.setProperty('color', '#000000', 'important');
              }
            }}
          >
            <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
            <span className="ml-1">{t('common.edit')}</span>
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleDelete(record.id!, record.label)}
            className="h-8 px-2 transition-colors hover:!text-[#1677ff] hover:!underline"
            style={{ color: '#000000' }}
            onMouseEnter={(e) => {
              const target = e.currentTarget as HTMLElement;
              target.style.setProperty('color', '#1677ff', 'important');
              target.style.setProperty('text-decoration', 'underline', 'important');
              const svg = target.querySelector('svg');
              if (svg) {
                svg.style.setProperty('color', '#1677ff', 'important');
              }
              const span = target.querySelector('span');
              if (span) {
                span.style.setProperty('color', '#1677ff', 'important');
              }
            }}
            onMouseLeave={(e) => {
              const target = e.currentTarget as HTMLElement;
              target.style.setProperty('color', '#000000', 'important');
              target.style.setProperty('text-decoration', 'none', 'important');
              const svg = target.querySelector('svg');
              if (svg) {
                svg.style.setProperty('color', '#000000', 'important');
              }
              const span = target.querySelector('span');
              if (span) {
                span.style.setProperty('color', '#000000', 'important');
              }
            }}
          >
            <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
            <span className="ml-1">{t('common.delete')}</span>
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      {/* 工具栏 */}
      <div className="flex justify-end">
        <Button
          onClick={() => openForm('create')}
          className="flex items-center gap-2"
        >
          <Plus className="w-4 h-4" />
          {t('form.addDictData')}
        </Button>
      </div>

      {/* 表格 */}
      <Table
        columns={columns}
        dataSource={list}
        rowKey="id"
        pagination={false}
        size="small"
        scroll={{ x: 1200 }}
      />

      {/* 表单弹窗 */}
      <DictDataForm ref={formRef} onSuccess={onRefresh} />
    </div>
  );
}

