import React, { useCallback, useEffect, useState } from 'react';
import {
  Button,
  Card,
  Descriptions,
  Popconfirm,
  Space,
  Spin,
  Switch,
  Table,
  Tag,
  Typography,
  message,
} from 'antd';
import {
  ArrowLeftOutlined,
  DeleteOutlined,
  EditOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { customRequest } from 'helpers/http';

const { Title } = Typography;

interface NodeInstance {
  id: string;
  nodeTypeId: string;
  name: string;
  description: string | null;
  config: Record<string, any>;
  isEnabled: boolean;
  creator: string;
  createdAt: string;
  updatedAt: string;
  nodeType?: {
    label: string;
    category: string;
    configSchema: Record<string, any>;
  };
}

export default function NodeInstanceShowPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [record, setRecord] = useState<NodeInstance | null>(null);
  const [loading, setLoading] = useState(true);
  const [references, setReferences] = useState<
    {
      workflowId: string;
      workflowName: string;
      version: number;
      nodeId: string;
      nodeLabel: string;
    }[]
  >([]);
  const [refsLoading, setRefsLoading] = useState(false);

  const fetchRecord = useCallback(async () => {
    setLoading(true);
    try {
      const res = await customRequest<NodeInstance>(
        `workflowNodeInstance/findUnique/${id}`,
        'POST',
        {
          id: true,
          nodeTypeId: true,
          name: true,
          description: true,
          config: true,
          isEnabled: true,
          creator: true,
          createdAt: true,
          updatedAt: true,
          nodeType: {
            select: { label: true, category: true, configSchema: true },
          },
        },
      );
      setRecord(res);
    } catch (e: any) {
      message.error(e?.message ?? 'Failed to load');
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  useEffect(() => {
    if (!id) return;
    setRefsLoading(true);
    customRequest<any[]>(`workflowNodeInstance/${id}/references`, 'POST')
      .then((res) => setReferences(Array.isArray(res) ? res : []))
      .catch(() => setReferences([]))
      .finally(() => setRefsLoading(false));
  }, [id]);

  async function handleDelete() {
    try {
      await customRequest(`workflowNodeInstance/deleteUnique/${id}`, 'DELETE');
      message.success('Deleted');
      navigate('/admin/workflow/node-instances');
    } catch (e: any) {
      message.error(e?.message ?? 'Delete failed');
    }
  }

  if (loading) {
    return (
      <div
        style={{ display: 'flex', justifyContent: 'center', paddingTop: 120 }}
      >
        <Spin size="large" />
      </div>
    );
  }

  if (!record) {
    return <div style={{ padding: 24 }}>Record not found</div>;
  }

  const configSchema = record.nodeType?.configSchema as any;
  const configProperties = configSchema?.properties ?? {};
  const configData: Record<string, any> =
    typeof record.config === 'string'
      ? (() => {
          try {
            return JSON.parse(record.config);
          } catch {
            return {};
          }
        })()
      : (record.config ?? {});

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 64px)' }}>
      <Card style={{ marginBottom: 16 }}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Space>
            <Button
              type="text"
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/admin/workflow/node-instances')}
            >
              Back
            </Button>
            <Title level={4} style={{ margin: 0 }}>
              {record.name}
            </Title>
          </Space>
          <Space>
            <Button
              icon={<EditOutlined />}
              onClick={() =>
                navigate(`/admin/workflow/node-instances/edit/${id}`)
              }
            >
              Edit
            </Button>
            <Popconfirm
              title="Delete this instance?"
              description="This action cannot be undone."
              okText="Delete"
              cancelText="Cancel"
              okButtonProps={{ danger: true }}
              onConfirm={handleDelete}
            >
              <Button danger icon={<DeleteOutlined />}>
                Delete
              </Button>
            </Popconfirm>
          </Space>
        </div>
      </Card>

      <Card title="Basic Info" style={{ marginBottom: 16 }}>
        <Descriptions column={2}>
          <Descriptions.Item label="Name">{record.name}</Descriptions.Item>
          <Descriptions.Item label="Node Type">
            <Space>
              <span>{record.nodeType?.label ?? '—'}</span>
              {record.nodeType?.category && (
                <Tag color="blue">{record.nodeType.category}</Tag>
              )}
            </Space>
          </Descriptions.Item>
          <Descriptions.Item label="Description">
            {record.description || '—'}
          </Descriptions.Item>
          <Descriptions.Item label="Enabled">
            <Switch size="small" checked={record.isEnabled} disabled />
          </Descriptions.Item>
          <Descriptions.Item label="Creator">
            {record.creator || '—'}
          </Descriptions.Item>
          <Descriptions.Item label="Created">
            {new Date(record.createdAt).toLocaleString()}
          </Descriptions.Item>
          <Descriptions.Item label="Updated">
            {new Date(record.updatedAt).toLocaleString()}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      <Card title="Configuration">
        {Object.keys(configData).length === 0 ? (
          <span style={{ color: '#999' }}>No configuration</span>
        ) : (
          <Descriptions column={1} bordered size="small">
            {Object.entries(configData).map(([key, value]) => {
              const prop = configProperties[key];
              const label = prop?.title || key;
              const displayValue =
                typeof value === 'boolean'
                  ? value
                    ? 'Yes'
                    : 'No'
                  : Array.isArray(value)
                    ? value.join(', ')
                    : String(value ?? '—');
              return (
                <Descriptions.Item key={key} label={label}>
                  {displayValue}
                </Descriptions.Item>
              );
            })}
          </Descriptions>
        )}
      </Card>

      <Card title="Referenced By" style={{ marginTop: 16 }}>
        {refsLoading ? (
          <Spin size="small" />
        ) : references.length === 0 ? (
          <span style={{ color: '#999' }}>暂无工作流引用此实例</span>
        ) : (
          <Table
            dataSource={references}
            rowKey={(r) => `${r.workflowId}-${r.nodeId}`}
            pagination={false}
            size="small"
            columns={[
              {
                title: 'Workflow',
                dataIndex: 'workflowName',
                render: (name: string, record: any) => (
                  <a
                    onClick={() =>
                      navigate(`/admin/workflow/show/${record.workflowId}`)
                    }
                  >
                    <LinkOutlined style={{ marginRight: 4 }} />
                    {name}
                  </a>
                ),
              },
              {
                title: 'Version',
                dataIndex: 'version',
                width: 80,
                render: (v: number) => `v${v}`,
              },
              {
                title: 'Node',
                dataIndex: 'nodeLabel',
              },
            ]}
          />
        )}
      </Card>
    </div>
  );
}
