import React, { useEffect, useState } from 'react';
import { Show } from "@refinedev/antd";
import { useShow, useMany } from "@refinedev/core";
import { Card, Descriptions, Space, Tag, Typography, Table, Button, Tooltip } from 'antd';
import { RefreshButton, DateField } from '@refinedev/antd';
import { ApiOutlined, LinkOutlined, InfoCircleOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

export const BlueprintShow = () => {
  const { queryResult } = useShow();
  const { data, isLoading } = queryResult;
  const record = data?.data;
  
  // Extract component IDs from the blueprint config
  const componentIds = record?.config?.components?.map((component: {id: string}) => component.id) || [];
  
  // Fetch component details for all component IDs
  const { data: componentsData, isLoading: componentsLoading } = useMany({
    resource: "components",
    ids: componentIds,
    queryOptions: {
      enabled: componentIds.length > 0,
    },
  });

  return (
    <Show
      isLoading={isLoading}
      headerButtons={[
        <Button 
          key="deploy" 
          type="primary" 
          icon={<ApiOutlined />} 
          href={`/deployments/create?blueprintId=${record?.id}`}
        >
          Deploy
        </Button>,
        <RefreshButton key="refresh" />
      ]}
    >
      <Title level={4}>Blueprint Details</Title>
      
      <Card style={{ marginBottom: 20 }}>
        <Descriptions bordered column={2}>
          <Descriptions.Item label="ID">{record?.id}</Descriptions.Item>
          <Descriptions.Item label="Name">{record?.name}</Descriptions.Item>
          <Descriptions.Item label="Version">{record?.version}</Descriptions.Item>
          <Descriptions.Item label="Components">
            <Tag color="blue">{record?.config?.components?.length || 0} Components</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Network Policies">
            <Tag color="purple">{record?.config?.networkPolicies?.length || 0} Policies</Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Description" span={2}>
            {record?.description}
          </Descriptions.Item>
        </Descriptions>
      </Card>
      
      <Card title="Components" style={{ marginBottom: 20 }}>
        {record?.config?.components && 
          <Table 
            dataSource={record.config.components.map((component: any) => {
              // Find the full component details from the components data
              const componentDetails = componentsData?.data?.find((c: any) => c.id === component.id);
              
              return {
                ...component,
                componentDetails,
              };
            })}
            rowKey="id"
            loading={componentsLoading}
            pagination={false}
            expandable={{
              expandedRowRender: (record: any) => (
                <Card type="inner" title="Component Details">
                  <Descriptions bordered column={2} size="small">
                    <Descriptions.Item label="Description">{record.componentDetails?.description}</Descriptions.Item>
                    <Descriptions.Item label="Language">{record.componentDetails?.language}</Descriptions.Item>
                    <Descriptions.Item label="Type">{record.componentDetails?.type}</Descriptions.Item>
                    <Descriptions.Item label="Version">{record.componentDetails?.version}</Descriptions.Item>
                  </Descriptions>
                </Card>
              ),
            }}
          >
            <Table.Column title="ID" dataIndex="id" />
            <Table.Column 
              title="Name" 
              dataIndex="name" 
              render={(value, record: any) => (
                <Space>
                  {value}
                  {record.componentDetails && (
                    <Tooltip title="View Component Details">
                      <Button 
                        type="link" 
                        icon={<InfoCircleOutlined />} 
                        href={`/components/show/${record.id}`} 
                        size="small"
                      />
                    </Tooltip>
                  )}
                </Space>
              )}
            />
            <Table.Column 
              title="Component Type" 
              render={(_, record: any) => (
                <Tag color="blue">{record.componentDetails?.type || "unknown"}</Tag>
              )}
            />
            <Table.Column 
              title="Public Access" 
              dataIndex="publicAccess" 
              render={(value) => value ? <Tag color="green">Yes</Tag> : <Tag color="red">No</Tag>}
            />
            <Table.Column 
              title="Resources" 
              dataIndex="resources" 
              render={(resources) => (
                <>
                  <div>CPU: {resources.cpu}</div>
                  <div>Memory: {resources.memory}</div>
                  <div>Storage: {resources.storage}</div>
                </>
              )} 
            />
            <Table.Column 
              title="Autoscaling" 
              dataIndex="autoscaling" 
              render={(autoscaling) => autoscaling?.enabled ? (
                <>
                  <div>Min: {autoscaling.minReplicas}</div>
                  <div>Max: {autoscaling.maxReplicas}</div>
                  <div>CPU: {autoscaling.cpuThreshold}%</div>
                </>
              ) : <Tag color="red">Disabled</Tag>} 
            />
          </Table>
        }
      </Card>
      
      <Card title="Network Policies" style={{ marginBottom: 20 }}>
        {record?.config?.networkPolicies && 
          <Table 
            dataSource={record.config.networkPolicies}
            rowKey="name"
            pagination={false}
          >
            <Table.Column title="Name" dataIndex="name" />
            <Table.Column 
              title="Sources" 
              dataIndex="sourceComponents" 
              render={(sources) => sources?.map((src: string) => <Tag key={src}>{src}</Tag>)}
            />
            <Table.Column 
              title="Targets" 
              dataIndex="targetComponents" 
              render={(targets) => targets?.map((target: string) => <Tag key={target}>{target}</Tag>)}
            />
            <Table.Column 
              title="Ports" 
              dataIndex="ports" 
              render={(ports) => ports?.map((port: number) => <Tag key={port}>{port}</Tag>)}
            />
            <Table.Column 
              title="Action" 
              dataIndex="action" 
              render={(action) => action === 'allow' ? 
                <Tag color="green">Allow</Tag> : 
                <Tag color="red">Deny</Tag>
              }
            />
          </Table>
        }
      </Card>
      
      <Card title="Environment Variables" style={{ marginBottom: 20 }}>
        {record?.config?.envVariables && 
          <Table 
            dataSource={Object.entries(record.config.envVariables).map(([key, value]) => ({ key, value }))}
            rowKey="key"
            pagination={false}
          >
            <Table.Column title="Key" dataIndex="key" />
            <Table.Column title="Value" dataIndex="value" />
          </Table>
        }
        {(!record?.config?.envVariables || Object.keys(record.config.envVariables).length === 0) && 
          <Text type="secondary">No environment variables defined</Text>
        }
      </Card>
      
      <Card title="Secrets" style={{ marginBottom: 20 }}>
        {record?.config?.secrets && 
          <Table 
            dataSource={record.config.secrets}
            rowKey="name"
            pagination={false}
          >
            <Table.Column title="Name" dataIndex="name" />
            <Table.Column title="Type" dataIndex="type" />
            <Table.Column title="Mount Path" dataIndex="mountPath" />
          </Table>
        }
        {(!record?.config?.secrets || record.config.secrets.length === 0) && 
          <Text type="secondary">No secrets defined</Text>
        }
      </Card>
      
      <Card title="Metadata">
        <Descriptions bordered column={2}>
          <Descriptions.Item label="Created At">
            <DateField value={record?.createdAt} format="LLL" />
          </Descriptions.Item>
          <Descriptions.Item label="Updated At">
            <DateField value={record?.updatedAt} format="LLL" />
          </Descriptions.Item>
          <Descriptions.Item label="Created By">{record?.createdBy}</Descriptions.Item>
        </Descriptions>
      </Card>
    </Show>
  );
};
