import { ApiOutlined, PlayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { App, Button, Card, Drawer, Empty, Flex, Form, List, Modal, Segmented, Space, Tag, Typography } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { apiRequest } from '../api/http';
import { groupForOperation, platformGroups, type PlatformGroupKey } from '../api/groups';
import { platformOperations } from '../api/platform-operations.generated';
import type { OperationInput, PlatformOperation } from '../api/types';
import { OperationForm, normalizeOperationInput } from '../components/OperationForm';
import { ResponseView } from '../components/ResponseView';

const methodColors: Record<string, string> = { GET: 'blue', POST: 'green', PUT: 'orange', PATCH: 'gold', DELETE: 'red' };

export function WorkspacePage({ groupKey }: { groupKey: PlatformGroupKey }) {
  const group = platformGroups.find((item) => item.key === groupKey)!;
  const operations = useMemo(() => platformOperations.filter((operation) => groupForOperation(operation) === groupKey), [groupKey]);
  const [selectedId, setSelectedId] = useState(operations[0]?.id || '');
  const [payload, setPayload] = useState<unknown>(undefined);
  const [loading, setLoading] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [methodFilter, setMethodFilter] = useState<string>('全部');
  const [form] = Form.useForm<OperationInput>();
  const { message, modal } = App.useApp();
  const selected = operations.find((operation) => operation.id === selectedId) || operations[0];
  const visibleOperations = methodFilter === '全部' ? operations : operations.filter((operation) => operation.method === methodFilter);

  useEffect(() => {
    setSelectedId(operations[0]?.id || '');
    setPayload(undefined);
  }, [operations]);

  const execute = async (operation: PlatformOperation, values: OperationInput) => {
    setLoading(true);
    try {
      const result = await apiRequest(operation, normalizeOperationInput(operation, values));
      setPayload(result);
      setDrawerOpen(false);
      message.success(`${operation.summary}完成`);
    } catch (error) {
      message.error(error instanceof Error ? error.message : '接口调用失败');
    } finally {
      setLoading(false);
    }
  };

  const submit = async () => {
    if (!selected) return;
    const values = await form.validateFields();
    if (selected.method !== 'GET') {
      modal.confirm({
        title: `确认执行：${selected.summary}`,
        content: `将调用 ${selected.method} ${selected.path}`,
        okText: '确认执行',
        cancelText: '取消',
        okButtonProps: { danger: /archive|disable|status/.test(selected.path) },
        onOk: () => execute(selected, values),
      });
      return;
    }
    await execute(selected, values);
  };

  const chooseOperation = (operation: PlatformOperation) => {
    setSelectedId(operation.id);
    setPayload(undefined);
    form.resetFields();
    setDrawerOpen(true);
  };

  if (!selected) return <Empty description="当前页面没有后端接口" />;
  return (
    <div className="workspace-page">
      <Flex justify="space-between" align="end" gap={16} wrap>
        <div>
          <Typography.Title level={2}>{group.label}</Typography.Title>
          <Typography.Text type="secondary">{group.description} · {operations.length} 个后端接口</Typography.Text>
        </div>
        <Segmented value={methodFilter} onChange={(value) => setMethodFilter(String(value))} options={['全部', ...new Set(operations.map((item) => item.method))]} />
      </Flex>
      <div className="workspace-grid">
        <Card className="operation-list-card" title="接口操作" extra={<ApiOutlined />}>
          <List
            dataSource={visibleOperations}
            renderItem={(operation) => (
              <List.Item className={operation.id === selected.id ? 'operation-active' : ''} onClick={() => chooseOperation(operation)}>
                <List.Item.Meta
                  title={<Space><Tag color={methodColors[operation.method]}>{operation.method}</Tag><span>{operation.summary}</span></Space>}
                  description={<Typography.Text type="secondary" ellipsis>{operation.path}</Typography.Text>}
                />
              </List.Item>
            )}
          />
        </Card>
        <Card
          className="response-card"
          title={payload === undefined ? '执行结果' : selected.summary}
          extra={payload !== undefined && <Button icon={<ReloadOutlined />} onClick={() => chooseOperation(selected)}>重新执行</Button>}
        >
          <ResponseView payload={payload} />
        </Card>
      </div>
      <Drawer
        title={selected.summary}
        width={560}
        open={drawerOpen}
        onClose={() => setDrawerOpen(false)}
        extra={<Tag color={methodColors[selected.method]}>{selected.method}</Tag>}
        footer={<Flex justify="end" gap={8}><Button onClick={() => setDrawerOpen(false)}>取消</Button><Button type="primary" icon={<PlayCircleOutlined />} loading={loading} onClick={() => void submit()}>执行</Button></Flex>}
      >
        <Typography.Paragraph type="secondary">{selected.description}</Typography.Paragraph>
        <Typography.Paragraph code copyable>{selected.path}</Typography.Paragraph>
        <Form form={form} layout="vertical" requiredMark="optional"><OperationForm operation={selected} /></Form>
      </Drawer>
    </div>
  );
}
