import {
  addApp,
  queryAppList,
  queryAppStats,
  removeApp,
  updateApp,
  updateAppStatus,
} from '@/services/project';
import {
  AppstoreOutlined,
  DeleteOutlined,
  DesktopOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  LinkOutlined,
  MobileOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined,
  PlusOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import {
  ModalForm,
  PageContainer,
  ProCard,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  QueryFilter,
} from '@ant-design/pro-components';
import { useIntl, useRequest } from '@umijs/max';
import {
  Button,
  Col,
  message,
  Modal,
  Pagination,
  Row,
  Space,
  Statistic,
  Tag,
  theme,
  Tooltip,
  Typography,
} from 'antd';
import React, { useEffect, useState } from 'react';
import type {
  AppItem,
  AppList,
  AppParams,
  AppSearchValues,
  AppStats,
  AppStatus,
} from './data';

const { Text, Paragraph } = Typography;
const { confirm } = Modal;

// 应用类型常量
const APP_TYPE_OPTIONS = [
  { label: 'PC端', value: 'pc' },
  { label: 'H5', value: 'h5' },
  { label: '小程序', value: 'miniapp' },
  { label: 'WebApp', value: 'webapp' },
];

// 应用状态常量
const APP_STATUS_OPTIONS = [
  { label: '开发中', value: 'developing' },
  { label: '已上线', value: 'online' },
  { label: '已下架', value: 'offline' },
  { label: '维护中', value: 'maintenance' },
];

// 状态映射（用于显示）
const STATUS_MAP: Record<
  AppStatus,
  { text: string; color: 'processing' | 'success' | 'default' | 'warning' }
> = {
  developing: { text: '开发中', color: 'processing' },
  online: { text: '已上线', color: 'success' },
  offline: { text: '已下架', color: 'default' },
  maintenance: { text: '维护中', color: 'warning' },
};

// 应用类型映射（用于显示）
const APP_TYPE_MAP: Record<string, { text: string; icon: React.ReactNode }> = {
  pc: { text: 'PC端', icon: <DesktopOutlined /> },
  h5: { text: 'H5', icon: <MobileOutlined /> },
  miniapp: { text: '小程序', icon: <AppstoreOutlined /> },
  webapp: { text: 'WebApp', icon: <LinkOutlined /> },
};

// 默认应用图标
const DEFAULT_APP_ICON = <AppstoreOutlined />;

const ProjectManagement: React.FC = () => {
  const intl = useIntl();
  const { token } = theme.useToken();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<AppItem | undefined>();
  const [searchParams, setSearchParams] = useState<AppSearchValues>({});
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 12,
    total: 0,
  });

  // 统计数据
  const [stats, setStats] = useState<AppStats>({
    total: 0,
    online: 0,
    developing: 0,
    offline: 0,
    maintenance: 0,
  });

  // 使用 useRequest 获取应用列表
  const { data: appList, run: loadAppList } = useRequest(
    (params: AppParams) => queryAppList(params),
    {
      manual: true,
      onSuccess: (data) => {
        if (data && typeof data === 'object' && 'data' in data) {
          const res = data as unknown as AppList;
          setPagination({
            current: res.current || 1,
            pageSize: res.pageSize || 12,
            total: res.total,
          });
        }
      },
    },
  );

  // 使用 useRequest 获取统计数据
  const { run: loadStats } = useRequest(() => queryAppStats(), {
    manual: true,
    onSuccess: (data) => {
      if (data && typeof data === 'object' && 'stats' in data) {
        setStats((data as unknown as { stats: AppStats }).stats);
      }
    },
  });

  // 初始加载
  useEffect(() => {
    loadAppList({ current: 1, pageSize: 12 });
    loadStats();
  }, []);

  // 搜索处理
  const handleSearch = async (values: AppSearchValues) => {
    setSearchParams(values);
    setCurrentRow(undefined);
    await loadAppList({ ...values, current: 1, pageSize: 12 });
    await loadStats();
  };

  // 分页处理
  const handlePageChange = (page: number, size: number) => {
    loadAppList({ current: page, pageSize: size, ...searchParams });
  };

  // 新增/编辑提交
  const handleSubmit = async (values: Partial<AppItem>) => {
    try {
      if (currentRow) {
        await updateApp({ ...currentRow, ...values });
        message.success(
          intl.formatMessage({
            id: 'project.message.updateSuccess',
            defaultMessage: '更新成功',
          }),
        );
      } else {
        await addApp(values);
        message.success(
          intl.formatMessage({
            id: 'project.message.createSuccess',
            defaultMessage: '创建成功',
          }),
        );
      }
      setModalVisible(false);
      loadAppList({
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams,
      });
      loadStats();
      return true;
    } catch {
      message.error(
        intl.formatMessage({
          id: 'project.message.operationError',
          defaultMessage: '操作失败',
        }),
      );
      return false;
    }
  };

  // 删除应用
  const handleDelete = (record: AppItem) => {
    confirm({
      title: intl.formatMessage({
        id: 'project.confirm.delete',
        defaultMessage: '确认删除',
      }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage(
        { id: 'project.confirm.delete.content' },
        { appName: record.appName },
      ),
      okText: intl.formatMessage({
        id: 'common.confirm',
        defaultMessage: '确认',
      }),
      okType: 'danger',
      cancelText: intl.formatMessage({
        id: 'common.cancel',
        defaultMessage: '取消',
      }),
      async onOk() {
        try {
          await removeApp(record.id);
          message.success(
            intl.formatMessage({
              id: 'project.message.deleteSuccess',
              defaultMessage: '删除成功',
            }),
          );
          loadAppList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            ...searchParams,
          });
          loadStats();
        } catch {
          message.error(
            intl.formatMessage({
              id: 'project.message.deleteError',
              defaultMessage: '删除失败',
            }),
          );
        }
      },
    });
  };

  // 启动/停止应用
  const handleToggleStatus = (record: AppItem) => {
    const newStatus: AppStatus =
      record.status === 'online' ? 'offline' : 'online';
    const isOnline = newStatus === 'online';

    confirm({
      title: isOnline
        ? intl.formatMessage({
            id: 'project.confirm.online',
            defaultMessage: '确认上线',
          })
        : intl.formatMessage({
            id: 'project.confirm.offline',
            defaultMessage: '确认下架',
          }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage(
        { id: 'project.confirm.delete.content' },
        { appName: record.appName },
      ),
      okText: intl.formatMessage({
        id: 'common.confirm',
        defaultMessage: '确认',
      }),
      cancelText: intl.formatMessage({
        id: 'common.cancel',
        defaultMessage: '取消',
      }),
      async onOk() {
        try {
          await updateAppStatus(record.id, newStatus);
          message.success(
            isOnline
              ? intl.formatMessage({
                  id: 'project.message.onlineSuccess',
                  defaultMessage: '上线成功',
                })
              : intl.formatMessage({
                  id: 'project.message.offlineSuccess',
                  defaultMessage: '下架成功',
                }),
          );
          loadAppList({
            current: pagination.current,
            pageSize: pagination.pageSize,
            ...searchParams,
          });
          loadStats();
        } catch {
          message.error(
            isOnline
              ? intl.formatMessage({
                  id: 'project.message.onlineError',
                  defaultMessage: '上线失败',
                })
              : intl.formatMessage({
                  id: 'project.message.offlineError',
                  defaultMessage: '下架失败',
                }),
          );
        }
      },
    });
  };

  return (
    <PageContainer header={{ title: false }}>
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={12} sm={6}>
          <ProCard hoverable>
            <Statistic
              title={intl.formatMessage({ id: 'project.stats.total' })}
              value={stats.total}
              prefix={<AppstoreOutlined />}
            />
          </ProCard>
        </Col>
        <Col xs={12} sm={6}>
          <ProCard hoverable>
            <Statistic
              title={intl.formatMessage({ id: 'project.stats.online' })}
              value={stats.online}
              valueStyle={{ color: token.colorSuccess }}
              prefix={<PlayCircleOutlined />}
            />
          </ProCard>
        </Col>
        <Col xs={12} sm={6}>
          <ProCard hoverable>
            <Statistic
              title={intl.formatMessage({ id: 'project.stats.developing' })}
              value={stats.developing}
              valueStyle={{ color: token.colorPrimary }}
              prefix={<SettingOutlined />}
            />
          </ProCard>
        </Col>
        <Col xs={12} sm={6}>
          <ProCard hoverable>
            <Statistic
              title={intl.formatMessage({ id: 'project.stats.maintenance' })}
              value={stats.maintenance}
              valueStyle={{ color: token.colorWarning }}
              prefix={<DesktopOutlined />}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 搜索区域 */}
      <QueryFilter
        layout="vertical"
        onFinish={handleSearch}
        style={{
          background: token.colorBgContainer,
          padding: token.padding,
          marginBottom: token.marginLG,
        }}
      >
        <ProFormText
          name="appName"
          label={intl.formatMessage({ id: 'project.search.appName' })}
          placeholder={intl.formatMessage({
            id: 'project.search.appName.placeholder',
          })}
        />
        <ProFormText
          name="owner"
          label={intl.formatMessage({ id: 'project.search.owner' })}
          placeholder={intl.formatMessage({
            id: 'project.search.owner.placeholder',
          })}
        />
        <ProFormSelect
          name="appType"
          label={intl.formatMessage({ id: 'project.search.appType' })}
          placeholder={intl.formatMessage({
            id: 'project.search.appType.placeholder',
          })}
          options={APP_TYPE_OPTIONS}
        />
        <ProFormSelect
          name="status"
          label={intl.formatMessage({ id: 'project.search.status' })}
          placeholder={intl.formatMessage({
            id: 'project.search.status.placeholder',
          })}
          options={APP_STATUS_OPTIONS}
        />
      </QueryFilter>

      {/* 操作栏 */}
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <Text strong style={{ fontSize: 16 }}>
          {intl.formatMessage({ id: 'project.list.title' })}
        </Text>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setCurrentRow(undefined);
            setModalVisible(true);
          }}
        >
          {intl.formatMessage({ id: 'project.action.add' })}
        </Button>
      </div>

      {/* 应用卡片网格 */}
      <Row gutter={[16, 16]}>
        {((appList as AppItem[]) || []).map((app: AppItem) => (
          <Col key={app.id} xs={24} sm={12} md={8} lg={6}>
            <ProCard
              hoverable
              style={{ height: '100%' }}
              title={
                <Space>
                  <span style={{ fontSize: 18 }}>
                    {app.appIcon || DEFAULT_APP_ICON}
                  </span>
                  <Text strong ellipsis style={{ maxWidth: 180 }}>
                    {app.appName}
                  </Text>
                </Space>
              }
              extra={
                <Tag color={STATUS_MAP[app.status].color}>
                  {STATUS_MAP[app.status].text}
                </Tag>
              }
              actions={[
                <Tooltip
                  title={intl.formatMessage({
                    id: 'project.action.view',
                    defaultMessage: '查看',
                  })}
                  key="url"
                >
                  <Button
                    type="text"
                    icon={<LinkOutlined />}
                    onClick={() => window.open(app.url, '_blank')}
                    disabled={!app.url || app.status !== 'online'}
                  />
                </Tooltip>,
                <Tooltip
                  title={intl.formatMessage({
                    id: 'common.edit',
                    defaultMessage: '编辑',
                  })}
                  key="edit"
                >
                  <Button
                    type="text"
                    icon={<EditOutlined />}
                    onClick={() => {
                      setCurrentRow(app);
                      setModalVisible(true);
                    }}
                  />
                </Tooltip>,
                <Tooltip
                  title={
                    app.status === 'online'
                      ? intl.formatMessage({
                          id: 'project.action.offline',
                          defaultMessage: '下架',
                        })
                      : intl.formatMessage({
                          id: 'project.action.online',
                          defaultMessage: '上架',
                        })
                  }
                  key="toggle"
                >
                  <Button
                    type="text"
                    icon={
                      app.status === 'online' ? (
                        <PauseCircleOutlined />
                      ) : (
                        <PlayCircleOutlined />
                      )
                    }
                    onClick={() => handleToggleStatus(app)}
                  />
                </Tooltip>,
                <Tooltip
                  title={intl.formatMessage({
                    id: 'project.action.delete',
                    defaultMessage: '删除',
                  })}
                  key="delete"
                >
                  <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => handleDelete(app)}
                  />
                </Tooltip>,
              ]}
            >
              <div style={{ padding: '8px 0' }}>
                <Space style={{ marginBottom: 8 }}>
                  <Tag>
                    {APP_TYPE_MAP[app.appType]?.icon}
                    {APP_TYPE_MAP[app.appType]?.text}
                  </Tag>
                  <Text type="secondary">v{app.version}</Text>
                </Space>

                {app.appDesc && (
                  <Paragraph
                    type="secondary"
                    ellipsis={{ rows: 2 }}
                    style={{ marginBottom: 8, fontSize: 12 }}
                  >
                    {app.appDesc}
                  </Paragraph>
                )}

                <div style={{ marginBottom: 8 }}>
                  <Text type="secondary">
                    {intl.formatMessage({
                      id: 'project.list.owner',
                      defaultMessage: '负责人',
                    })}
                  </Text>
                  <Text>{app.owner}</Text>
                </div>

                {app.tags && app.tags.length > 0 && (
                  <div>
                    {app.tags.slice(0, 3).map((tag: string) => (
                      <Tag key={tag} style={{ marginTop: 4, fontSize: 11 }}>
                        {tag}
                      </Tag>
                    ))}
                  </div>
                )}
              </div>
            </ProCard>
          </Col>
        ))}
      </Row>

      {/* 分页 */}
      <div style={{ marginTop: 16, textAlign: 'right' }}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          onChange={handlePageChange}
          showSizeChanger
          showQuickJumper
          showTotal={(total) =>
            intl.formatMessage(
              {
                id: 'project.pagination.total',
                defaultMessage: '共 {total} 条',
              },
              { total },
            )
          }
        />
      </div>

      {/* 新增/编辑弹窗 */}
      <ModalForm
        title={
          currentRow
            ? intl.formatMessage({
                id: 'project.action.edit',
                defaultMessage: '编辑应用',
              })
            : intl.formatMessage({
                id: 'project.action.add',
                defaultMessage: '新增应用',
              })
        }
        width="500px"
        open={modalVisible}
        onOpenChange={setModalVisible}
        initialValues={currentRow}
        modalProps={{ destroyOnHidden: true }}
        onFinish={handleSubmit}
        layout="vertical"
      >
        <ProFormText
          name="appName"
          label={intl.formatMessage({ id: 'project.form.appName' })}
          placeholder={intl.formatMessage({
            id: 'project.form.appName.placeholder',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'project.form.appName.required',
              }),
            },
          ]}
        />
        <ProFormTextArea
          name="appDesc"
          label={intl.formatMessage({ id: 'project.form.appDesc' })}
          placeholder={intl.formatMessage({
            id: 'project.form.appDesc.placeholder',
          })}
        />
        <Space style={{ width: '100%' }} size={16}>
          <ProFormSelect
            name="appType"
            label={intl.formatMessage({ id: 'project.form.appType' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'project.form.appType.required',
                }),
              },
            ]}
            options={APP_TYPE_OPTIONS}
            style={{ width: '100%' }}
          />
          <ProFormSelect
            name="status"
            label={intl.formatMessage({ id: 'project.form.status' })}
            options={APP_STATUS_OPTIONS}
            initialValue="developing"
            style={{ width: '100%' }}
          />
        </Space>
        <ProFormText
          name="owner"
          label={intl.formatMessage({ id: 'project.form.owner' })}
          placeholder={intl.formatMessage({
            id: 'project.form.owner.placeholder',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'project.form.owner.required',
              }),
            },
          ]}
        />
        <ProFormText
          name="version"
          label={intl.formatMessage({ id: 'project.form.version' })}
          placeholder={intl.formatMessage({
            id: 'project.form.version.placeholder',
          })}
        />
        <ProFormText
          name="url"
          label={intl.formatMessage({ id: 'project.form.url' })}
          placeholder={intl.formatMessage({
            id: 'project.form.url.placeholder',
          })}
        />
        <ProFormText
          name="appIcon"
          label={intl.formatMessage({ id: 'project.form.appIcon' })}
          placeholder={intl.formatMessage({
            id: 'project.form.appIcon.placeholder',
          })}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default ProjectManagement;
