import { CopyOutlined } from '@ant-design/icons'
import { yaml } from '@codemirror/lang-yaml'
import CodeMirror from '@uiw/react-codemirror'
import { Card, Spin, Tabs, Button, message, Empty } from 'antd'
import Title from 'antd/lib/typography/Title'
import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'

import { listClusterResources } from 'apiClient/services/devops'
import { K8sresourceClusterResource } from 'apiClient/services/devops/interface'

export default function DataPlane() {
  const { cluster_id } = useParams<{ cluster_id: string }>()
  const [loading, setLoading] = useState(true)
  const [resources, setResources] = useState<K8sresourceClusterResource[]>([])

  useEffect(() => {
    fetchResources()
  }, [cluster_id])

  const fetchResources = async () => {
    try {
      setLoading(true)
      const response = await listClusterResources(cluster_id)
      if (response?.data?.resources) {
        setResources(response.data.resources)
      }
    } catch (error) {
      message.error('Failed to fetch cluster resources')
    } finally {
      setLoading(false)
    }
  }

  const handleCopy = (content: string) => {
    navigator.clipboard.writeText(content)
    message.success('Copied to clipboard')
  }

  if (loading) {
    return <Spin />
  }

  if (resources.length === 0) {
    return <Empty description="No cluster resources" />
  }

  const tabItems = resources.map((resource, index) => ({
    key: resource.key || `resource-${index}`,
    label: resource.display_name || resource.key || `Resource ${index + 1}`,
    children: (
      <div style={{ padding: '16px 0' }}>
        {resource.description && (
          <div style={{ marginBottom: '12px', color: '#666' }}>
            {resource.description}
          </div>
        )}
        <CodeMirror
          value={resource.content || ''}
          extensions={[yaml()]}
          readOnly
          basicSetup={{
            lineNumbers: true,
            foldGutter: true,
            highlightActiveLine: false
          }}
          style={{
            fontSize: '12px',
            marginBottom: '12px',
            border: '1px solid #d9d9d9',
            borderRadius: '4px'
          }}
        />
        <Button
          type="primary"
          icon={<CopyOutlined />}
          onClick={() => handleCopy(resource.content || '')}
        >
          Copy Content
        </Button>
      </div>
    )
  }))

  return (
    <Card bordered={false}>
      <Tabs items={tabItems} />
    </Card>
  )
}
