import React, { useState, type CSSProperties } from 'react'

import { Card, Collapse, Group, Text } from '@mantine/core'
import { IconChevronDown, IconChevronUp, IconServer } from '@tabler/icons-react'
import { Table, Tooltip } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { useQuery } from 'react-query'
import { useParams } from 'react-router-dom'

import type {
  ViewResourcePoolComponent,
  ViewResourcePoolImage
} from '@clinic/client'
import { getResourcePoolComponents } from '~/api'
import { useCurCluster, useUserStore } from '~/hooks/state'

const isPdComponent = (componentType?: string) =>
  componentType
    ?.trim()
    .toUpperCase()
    .replace(/^COMPONENT_TYPE_/, '') === 'PD'

export const ResourcePoolTopo: React.FC = () => {
  const { curCluster } = useCurCluster()
  const isInternalUser = useUserStore((state) => state.user?.internal)
  const { orgId } = useParams<'orgId'>()
  const [expanded, setExpanded] = useState(false)
  const { data, isLoading } = useQuery({
    queryKey: ['resourcePoolComponents', orgId, curCluster?.id],
    queryFn: () => getResourcePoolComponents(orgId!, curCluster?.id!),
    enabled: expanded // Only fetch when expanded
  })
  const hideDedicatedInternalDetails =
    !!curCluster?.computed.isDedicated && isInternalUser !== true
  const allComponents = data?.data || []
  const components = hideDedicatedInternalDetails
    ? allComponents.filter(
        (component) => !isPdComponent(component.component_type)
      )
    : allComponents

  const formatStorageInfo = (
    storages?: ViewResourcePoolComponent['storages']
  ) => {
    if (!storages || storages.length === 0) {
      return 'N/A'
    }
    return storages
      .map((storage) => {
        const parts: string[] = []
        if (storage.type) {
          parts.push(storage.type)
        }
        if (storage.size_gi) {
          parts.push(`${storage.size_gi}GiB`)
        }
        if (storage.iops) {
          parts.push(`${storage.iops} IOPS`)
        }
        if (storage.throughput_mbs) {
          parts.push(`${storage.throughput_mbs} MB/s`)
        }
        const content = parts.join(', ') || 'N/A'
        const name = storage.name
        return `${name}: ${content}`
      })
      .join('; ')
  }

  const formatComponentType = (componentType?: string) => {
    if (!componentType) return 'N/A'
    // Convert COMPONENT_TYPE_TIDB to TiDB, etc.
    return componentType
      .replace('COMPONENT_TYPE_', '')
      .split('_')
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
      .join(' ')
  }

  const fullImageRef = (image?: ViewResourcePoolImage) => {
    if (!image) return
    if (image.repo && image.tag) {
      return `${image.repo}:${image.tag}`
    }
    return image.repo || image.tag
  }

  const imageTagSpanBase: CSSProperties = {
    display: 'inline-block',
    maxWidth: 220,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    verticalAlign: 'bottom'
  }

  /** Dotted underline + help cursor: hints that hover shows the full image ref. */
  const imageTagSpanHint: CSSProperties = {
    ...imageTagSpanBase,
    cursor: 'help',
    textDecoration: 'underline',
    textDecorationStyle: 'dotted',
    textDecorationColor: 'rgba(0, 0, 0, 0.28)',
    textUnderlineOffset: 3
  }

  const renderImageColumn = (image?: ViewResourcePoolImage) => {
    const full = fullImageRef(image)
    const tagOnly = image?.tag?.trim()
    if (!tagOnly && !full) {
      return (
        <Text size='sm' c='dimmed' component='span'>
          N/A
        </Text>
      )
    }
    const cell = tagOnly || full || 'N/A'
    if (!full || full === cell) {
      return <span style={imageTagSpanBase}>{cell}</span>
    }
    return (
      <Tooltip title={full} placement='topLeft'>
        <span style={imageTagSpanHint}>{cell}</span>
      </Tooltip>
    )
  }

  const columns: ColumnsType<ViewResourcePoolComponent> = [
    {
      title: 'Component',
      dataIndex: 'component_type',
      key: 'component_type',
      render: (value) => formatComponentType(value)
    },
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: 'Phase',
      dataIndex: 'phase',
      key: 'phase'
    },
    {
      title: 'Image',
      dataIndex: 'image',
      key: 'image',
      render: (_, record) => renderImageColumn(record?.image)
    },
    {
      title: 'Max Node Count',
      dataIndex: 'max_node_count',
      key: 'max_node_count',
      align: 'right'
    },
    {
      title: 'Node Count',
      dataIndex: 'node_count',
      key: 'node_count',
      align: 'right'
    },
    {
      title: 'CPU Cores',
      dataIndex: 'cpu',
      key: 'cpu',
      align: 'right'
    },
    {
      title: 'Memory (GiB)',
      dataIndex: 'memory_gi',
      key: 'memory_gi',
      align: 'right'
    }
  ]
  if (!hideDedicatedInternalDetails) {
    columns.push({
      title: 'Storage Info',
      dataIndex: 'storages',
      key: 'storages',
      render: (storages) => formatStorageInfo(storages)
    })
  }

  return (
    <Card withBorder p={0}>
      <div
        style={{
          background: '#fff',
          cursor: 'pointer',
          userSelect: 'none',
          transition: 'background-color 0.2s ease',
          padding: '10px 14px'
        }}
        onClick={() => setExpanded(!expanded)}
        onMouseEnter={(e) => {
          e.currentTarget.style.backgroundColor = '#f3f4f6'
        }}
        onMouseLeave={(e) => {
          e.currentTarget.style.backgroundColor = '#fff'
        }}
      >
        <Group spacing='xs' position='apart' noWrap>
          <Group spacing='xs' noWrap>
            <IconServer
              size={16}
              style={{
                color: '#6b7280'
              }}
            />
            <Text size='sm' fw={500}>
              Topology Details
            </Text>
          </Group>
          {expanded ? (
            <IconChevronUp
              size={16}
              style={{
                color: '#6b7280',
                transition: 'transform 0.2s ease'
              }}
            />
          ) : (
            <IconChevronDown
              size={16}
              style={{
                color: '#6b7280',
                transition: 'transform 0.2s ease'
              }}
            />
          )}
        </Group>
      </div>
      <Collapse in={expanded}>
        <div style={{ padding: '16px', background: '#fff' }}>
          {isLoading ? (
            <Text size='sm' c='dimmed' ta='center' py='md'>
              Loading...
            </Text>
          ) : components.length === 0 ? (
            <Text size='sm' c='dimmed' ta='center' py='md'>
              No components found
            </Text>
          ) : (
            <Table
              columns={columns}
              dataSource={components}
              rowKey='id'
              pagination={false}
              size='small'
              scroll={{ x: 'max-content' }}
            />
          )}
        </div>
      </Collapse>
    </Card>
  )
}
