import {
  getSkillDetail,
  querySkillList,
  updateSkillStatus,
} from '@/services/skill';
import {
  ClockCircleOutlined,
  EyeOutlined,
  FileOutlined,
  FolderOutlined,
  ToolOutlined,
} from '@ant-design/icons';
import {
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Drawer, message, Space, Switch, Tag, theme } from 'antd';
import { useState } from 'react';
import type { SkillDetail, SkillItem, SkillType } from './data';

// 类型标签颜色映射
const typeColors: Record<SkillType, string> = {
  agent: 'purple',
  development: 'blue',
  design: 'cyan',
  document: 'green',
  testing: 'orange',
  integration: 'magenta',
  workflow: 'gold',
  utility: 'red',
};

// 类型名称映射
const typeLabels: Record<SkillType, string> = {
  agent: 'Agent',
  development: '开发',
  design: '设计',
  document: '文档',
  testing: '测试',
  integration: '集成',
  workflow: '工作流',
  utility: '工具',
};

const SkillManager: React.FC = () => {
  const intl = useIntl();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentSkill, setCurrentSkill] = useState<SkillDetail | null>(null);
  const [currentType, setCurrentType] = useState<string>('all');
  const { token } = theme.useToken();

  // 表格列定义
  const columns: ProColumns<SkillItem>[] = [
    {
      title: (
        <FormattedMessage id="pages.skill.name" defaultMessage="Skill 名称" />
      ),
      dataIndex: 'name',
      key: 'name',
      render: (_, record) => (
        <Space>
          <ToolOutlined style={{ color: token.colorPrimary }} />
          <span style={{ fontWeight: 600 }}>{record.name}</span>
        </Space>
      ),
      width: 200,
    },
    {
      title: (
        <FormattedMessage id="pages.skill.description" defaultMessage="描述" />
      ),
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 300,
    },
    {
      title: <FormattedMessage id="pages.skill.type" defaultMessage="类型" />,
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (_, record) => (
        <Tag color={typeColors[record.type]}>{typeLabels[record.type]}</Tag>
      ),
    },
    {
      title: <FormattedMessage id="pages.skill.source" defaultMessage="来源" />,
      dataIndex: 'source',
      key: 'source',
      width: 100,
      render: (_, record) => (
        <Tag color={record.source === 'agents' ? 'blue' : 'purple'}>
          {record.source === 'agents' ? 'Agents' : 'OpenCode'}
        </Tag>
      ),
    },
    {
      title: (
        <FormattedMessage id="pages.skill.fileCount" defaultMessage="文件数" />
      ),
      dataIndex: 'fileCount',
      key: 'fileCount',
      width: 100,
      render: (_, record) => (
        <Space>
          <FileOutlined />
          {record.fileCount}
        </Space>
      ),
      search: false,
    },
    {
      title: (
        <FormattedMessage
          id="pages.skill.lastModified"
          defaultMessage="更新时间"
        />
      ),
      dataIndex: 'lastModified',
      key: 'lastModified',
      width: 150,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.skill.status" defaultMessage="状态" />,
      dataIndex: 'isEnabled',
      key: 'isEnabled',
      width: 100,
      render: (_, record) => (
        <Switch
          checked={record.isEnabled}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={async (checked) => {
            try {
              await updateSkillStatus(record.id, checked);
              message.success(checked ? '已启用' : '已禁用');
            } catch (error) {
              message.error('操作失败');
            }
          }}
        />
      ),
    },
    {
      title: <FormattedMessage id="common.action" defaultMessage="操作" />,
      valueType: 'option',
      key: 'option',
      width: 100,
      render: (_, record) => [
        <a
          key="detail"
          onClick={async () => {
            const res = await getSkillDetail(record.id);
            setCurrentSkill(res.data);
            setDrawerVisible(true);
          }}
        >
          <EyeOutlined />{' '}
          <FormattedMessage id="common.view" defaultMessage="查看" />
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<SkillItem>
        headerTitle={
          <Space>
            <ToolOutlined style={{ color: token.colorPrimary }} />
            <FormattedMessage
              id="pages.skill.title"
              defaultMessage="Skill 管理"
            />
          </Space>
        }
        columns={columns}
        params={{ type: currentType }}
        request={async (params) => {
          const { current = 1, pageSize = 10, keyword, ...restParams } = params;
          const res = await querySkillList({
            ...restParams,
            current,
            pageSize,
            keyword,
          });
          return {
            data: res.data,
            success: true,
            total: res.total,
          };
        }}
        rowKey="id"
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
          style: {
            background: token.colorBgContainer,
            padding: token.padding,
            borderRadius: token.borderRadius,
            marginBottom: token.marginLG,
          },
          filterType: 'query',
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <Space.Compact key="filter">
            {[
              { key: 'all', label: '全部' },
              { key: 'agent', label: 'Agent' },
              { key: 'development', label: '开发' },
              { key: 'design', label: '设计' },
              { key: 'document', label: '文档' },
              { key: 'testing', label: '测试' },
              { key: 'integration', label: '集成' },
              { key: 'workflow', label: '工作流' },
              { key: 'utility', label: '工具' },
            ].map((item) => (
              <Tag.CheckableTag
                key={item.key}
                checked={currentType === item.key}
                onClick={() => setCurrentType(item.key)}
                style={{
                  padding: '4px 12px',
                  borderRadius: token.borderRadius,
                  cursor: 'pointer',
                }}
              >
                {item.label}
              </Tag.CheckableTag>
            ))}
          </Space.Compact>,
        ]}
      />

      <Drawer
        title={
          <FormattedMessage
            id="pages.skill.detail"
            defaultMessage="Skill 详情"
          />
        }
        placement="right"
        width={600}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          setCurrentSkill(null);
        }}
      >
        {currentSkill && (
          <ProDescriptions column={1} bordered size="small">
            <ProDescriptions.Item
              label={
                <FormattedMessage id="pages.skill.name" defaultMessage="名称" />
              }
            >
              {currentSkill.name}
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage
                  id="pages.skill.description"
                  defaultMessage="描述"
                />
              }
            >
              {currentSkill.description}
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage id="pages.skill.type" defaultMessage="类型" />
              }
            >
              <Tag color={typeColors[currentSkill.type]}>
                {typeLabels[currentSkill.type]}
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage
                  id="pages.skill.source"
                  defaultMessage="来源"
                />
              }
            >
              <Tag color={currentSkill.source === 'agents' ? 'blue' : 'purple'}>
                {currentSkill.source === 'agents' ? 'Agents' : 'OpenCode'}
              </Tag>
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage id="pages.skill.path" defaultMessage="路径" />
              }
            >
              <Space>
                <FolderOutlined />
                {currentSkill.path}
              </Space>
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage
                  id="pages.skill.fileCount"
                  defaultMessage="文件数"
                />
              }
            >
              <Space>
                <FileOutlined />
                {currentSkill.fileCount}
              </Space>
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage
                  id="pages.skill.lastModified"
                  defaultMessage="更新时间"
                />
              }
            >
              <Space>
                <ClockCircleOutlined />
                {new Date(currentSkill.lastModified).toLocaleString()}
              </Space>
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage
                  id="pages.skill.status"
                  defaultMessage="状态"
                />
              }
            >
              <Switch
                checked={currentSkill.isEnabled}
                checkedChildren="启用"
                unCheckedChildren="禁用"
                disabled
              />
            </ProDescriptions.Item>
            <ProDescriptions.Item
              label={
                <FormattedMessage id="pages.skill.tags" defaultMessage="标签" />
              }
            >
              <Space>
                {currentSkill.tags?.map((tag) => (
                  <Tag key={tag}>{tag}</Tag>
                ))}
              </Space>
            </ProDescriptions.Item>
          </ProDescriptions>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default SkillManager;
