import { useState, useCallback, useEffect } from 'react';
import { Button, Form, Input, InputNumber, message, Modal, Popconfirm, Result, Select, Space, Switch, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

import {
  oauthClientApi,
  type OAuthClient,
  type CreateOAuthClientReq,
  type UpdateOAuthClientReq,
  FHIR_SCOPE_OPTIONS,
} from '../../api/health/oauthClients';
import { PageContainer } from '../../components/PageContainer';
import { usePermission } from '../../hooks/usePermission';

export default function OAuthClientList() {
  const { hasPermission } = usePermission('health.oauth.manage');
  const [data, setData] = useState<OAuthClient[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editRecord, setEditRecord] = useState<OAuthClient | null>(null);
  const [form] = Form.useForm();

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const list = await oauthClientApi.list();
      setData(list);
    } catch {
      message.error('加载合作方列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleCreate = () => {
    setEditRecord(null);
    form.resetFields();
    setModalOpen(true);
  };

  const handleEdit = (record: OAuthClient) => {
    setEditRecord(record);
    form.setFieldsValue({
      client_name: record.client_name,
      scopes: record.scopes,
      rate_limit_per_minute: record.rate_limit_per_minute,
      token_lifetime_seconds: record.token_lifetime_seconds,
      is_active: record.is_active,
    });
    setModalOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editRecord) {
        const req: UpdateOAuthClientReq = {
          ...values,
          version: editRecord.version,
        };
        await oauthClientApi.update(editRecord.id, req);
        message.success('合作方已更新');
      } else {
        const req: CreateOAuthClientReq = values;
        const result = await oauthClientApi.create(req);
        Modal.success({
          title: '合作方已创建',
          content: (
            <div>
              <p><strong>Client ID:</strong> {result.client_id}</p>
              <p><strong>Client Secret:</strong> {result.client_secret}</p>
              <Typography.Text type="warning">请妥善保存 Secret，关闭后不可再次查看。</Typography.Text>
            </div>
          ),
        });
      }
      setModalOpen(false);
      fetchData();
    } catch {
      // 表单校验失败
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await oauthClientApi.delete(id);
      message.success('合作方已删除');
      fetchData();
    } catch {
      message.error('删除失败');
    }
  };

  const handleRegenerate = async (record: OAuthClient) => {
    try {
      const result = await oauthClientApi.regenerateSecret(record.id);
      Modal.info({
        title: 'Secret 已重新生成',
        content: (
          <div>
            <p><strong>新 Client Secret:</strong></p>
            <Typography.Text copyable code>{result.client_secret}</Typography.Text>
          </div>
        ),
      });
    } catch {
      message.error('重新生成 Secret 失败');
    }
  };

  const columns: ColumnsType<OAuthClient> = [
    {
      title: '名称',
      dataIndex: 'client_name',
      width: 160,
    },
    {
      title: 'Client ID',
      dataIndex: 'client_id',
      width: 200,
      render: (v: string) => <Typography.Text copyable code>{v}</Typography.Text>,
    },
    {
      title: 'Scope',
      dataIndex: 'scopes',
      width: 250,
      render: (scopes: string[]) =>
        scopes.map((s) => <Tag key={s} color="blue">{s}</Tag>),
    },
    {
      title: '限流 (次/分)',
      dataIndex: 'rate_limit_per_minute',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 80,
      render: (v: boolean) => <Tag color={v ? 'green' : 'default'}>{v ? '启用' : '禁用'}</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 170,
      render: (v: string) => dayjs(v).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      width: 220,
      render: (_, record) => (
        <Space>
          <Button size="small" onClick={() => handleEdit(record)}>编辑</Button>
          <Button size="small" onClick={() => handleRegenerate(record)}>重置 Secret</Button>
          <Popconfirm title="确定删除此合作方？" onConfirm={() => handleDelete(record.id)}>
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  if (!hasPermission) {
    return <Result status="403" title="权限不足" subTitle="您没有管理 FHIR API 合作方的权限" />;
  }

  return (
    <PageContainer
      title="FHIR API 合作方管理"
      actions={<Button type="primary" onClick={handleCreate}>创建合作方</Button>}
    >
      <Table<OAuthClient>
        rowKey="id"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={false}
      />

      <Modal
        title={editRecord ? '编辑合作方' : '创建合作方'}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={() => setModalOpen(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="client_name" label="合作方名称" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="如：XX医院HIS系统" />
          </Form.Item>
          <Form.Item name="scopes" label="FHIR Scope" rules={[{ required: true, message: '请选择至少一个 scope' }]}>
            <Select mode="multiple" options={FHIR_SCOPE_OPTIONS} placeholder="选择允许的 FHIR 资源" />
          </Form.Item>
          <Form.Item name="rate_limit_per_minute" label="限流 (次/分钟)" initialValue={60}>
            <InputNumber min={1} max={1000} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="token_lifetime_seconds" label="Token 有效期 (秒)" initialValue={3600}>
            <InputNumber min={60} max={86400} style={{ width: '100%' }} />
          </Form.Item>
          {editRecord && (
            <Form.Item name="is_active" label="启用状态" valuePropName="checked">
              <Switch />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </PageContainer>
  );
}
