import { Card, Descriptions, Table, Typography, Button, Space, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { CopyOutlined, LinkOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { fetchGrafanaConfig, type GrafanaDashboard } from '../../api/grafana';

const { Text, Paragraph } = Typography;

interface DashboardRow extends GrafanaDashboard {
  url: string;
}

export function GrafanaInfoCard() {
  const { data, isLoading } = useQuery({ queryKey: ['grafana-config'], queryFn: fetchGrafanaConfig });

  const baseUrl = data?.baseUrl?.replace(/\/$/, '') ?? '';
  const rows: DashboardRow[] = (data?.dashboards ?? []).map((d) => ({
    ...d,
    url: baseUrl ? `${baseUrl}/d/${encodeURIComponent(d.uid)}?orgId=1&kiosk=tv&theme=light` : '',
  }));

  const copy = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      message.success('Copied');
    } catch {
      message.error('Copy failed');
    }
  };

  const columns: ColumnsType<DashboardRow> = [
    { title: 'Title', dataIndex: 'title', key: 'title' },
    { title: 'UID', dataIndex: 'uid', key: 'uid' },
    { title: 'Description', dataIndex: 'description', key: 'desc' },
    {
      title: 'Embed URL',
      dataIndex: 'url',
      key: 'url',
      render: (url: string) => (
        <Space>
          <Text code style={{ fontSize: 11 }}>{url}</Text>
          <Button size="small" icon={<CopyOutlined />} onClick={() => copy(url)} />
        </Space>
      ),
    },
  ];

  return (
    <Card loading={isLoading}>
      <Descriptions title="Grafana" column={1} size="small" bordered style={{ marginBottom: 16 }}>
        <Descriptions.Item label="Base URL">
          <Space>
            <Text code>{data?.baseUrl}</Text>
            {data?.baseUrl && (
              <Button size="small" icon={<LinkOutlined />} onClick={() => window.open(data.baseUrl, '_blank')}>
                Open
              </Button>
            )}
          </Space>
        </Descriptions.Item>
        <Descriptions.Item label="Default dashboard UID">
          <Text code>{data?.defaultDashboardUid || '(unset)'}</Text>
        </Descriptions.Item>
        <Descriptions.Item label="Dashboards configured">{data?.dashboards.length ?? 0}</Descriptions.Item>
      </Descriptions>

      <Paragraph type="secondary" style={{ fontSize: 12 }}>
        Add dashboards by dropping JSON into <Text code>grafana/dashboards/</Text> and adding a matching entry
        to <Text code>Grafana.Dashboards</Text> in configuration.
      </Paragraph>

      <Table<DashboardRow>
        rowKey="uid"
        size="small"
        columns={columns}
        dataSource={rows}
        pagination={false}
      />
    </Card>
  );
}
