import { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Button,
  Space,
  Row,
  Col,
  Spin,
  Radio,
  Alert,
} from 'antd';
import {
  ReloadOutlined,
  LinkOutlined,
  DashboardOutlined,
  AlertOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import duration from 'dayjs/plugin/duration';
import { api } from '@/lib/api';
import { buildServiceUrl } from '@/lib/service-url';
import { ServiceStatusCard } from '@/components/observability/ServiceStatusCard';
import { MetricsGrid } from '@/components/observability/MetricsGrid';
import { AlertsTable } from '@/components/observability/AlertsTable';
import { IframeErrorBoundary } from '@/components/observability/IframeErrorBoundary';
import type { AppOutletContext } from '@/components/AppLayout';
import type {
  ObservabilityStatus,
  MetricsSummary,
  AlertsResponse,
  ServiceStatus,
  ServicesConfig,
} from '@/types/api';

dayjs.extend(relativeTime);
dayjs.extend(duration);

type TabKey = 'overview' | 'monitoring' | 'alerts';

export default function ObservabilityPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [status, setStatus] = useState<ObservabilityStatus | null>(null);
  const [config, setConfig] = useState<ServicesConfig | null>(null);
  const [metrics, setMetrics] = useState<MetricsSummary | null>(null);
  const [alerts, setAlerts] = useState<AlertsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<TabKey>('overview');
  const [grafanaIframeSrc, setGrafanaIframeSrc] = useState<string | null>(null);
  const [alertmanagerIframeSrc, setAlertmanagerIframeSrc] = useState<string | null>(null);
  const grafanaInitialized = useRef(false);
  const alertmanagerInitialized = useRef(false);

  const fetchStatus = useCallback(async () => {
    try {
      const res = await api.get<ObservabilityStatus>('/observability/status');
      setStatus(res.data);
    } catch {
      // Status fetch failed — leave null
    }
  }, []);

  const fetchConfig = useCallback(async () => {
    try {
      const res = await api.get<ServicesConfig>('/services/config');
      setConfig(res.data);
    } catch {
      // Config fetch failed — leave null
    }
  }, []);

  const fetchMetrics = useCallback(async () => {
    try {
      const res = await api.get<MetricsSummary>('/observability/metrics-summary');
      setMetrics(res.data);
    } catch {
      // Metrics fetch may fail if Prometheus is offline
    }
  }, []);

  const fetchAlerts = useCallback(async () => {
    try {
      const res = await api.get<AlertsResponse>('/observability/alerts');
      setAlerts(res.data);
    } catch {
      // Alerts fetch may fail if Alertmanager is offline
    }
  }, []);

  const fetchAll = useCallback(async () => {
    setLoading(true);
    await Promise.all([fetchStatus(), fetchConfig(), fetchMetrics(), fetchAlerts()]);
    setLoading(false);
  }, [fetchStatus, fetchConfig, fetchMetrics, fetchAlerts]);

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

  // Lazy-load Grafana iframe
  useEffect(() => {
    if (activeTab === 'monitoring' && !grafanaInitialized.current && status?.grafana.online && config) {
      try {
        const baseUrl = buildServiceUrl(config.grafanaSubdomain, config.domain, config.grafanaPort);
        const url = `${baseUrl}/d/changemaker-overview/changemaker-overview`;
        setGrafanaIframeSrc(url);
        grafanaInitialized.current = true;
      } catch (error) {
        console.error('Failed to construct Grafana URL:', error);
      }
    }
  }, [activeTab, status, config]);

  // Lazy-load Alertmanager iframe
  useEffect(() => {
    if (activeTab === 'alerts' && !alertmanagerInitialized.current && status?.alertmanager.online && config) {
      try {
        const url = buildServiceUrl(config.alertmanagerSubdomain, config.domain, config.alertmanagerPort);
        setAlertmanagerIframeSrc(url);
        alertmanagerInitialized.current = true;
      } catch (error) {
        console.error('Failed to construct Alertmanager URL:', error);
      }
    }
  }, [activeTab, status, config]);

  // Set page header with tab switcher only
  useEffect(() => {
    setPageHeader({
      title: 'Observability',
      subtitle: 'System monitoring, metrics, and alerts',
      actions: (
        <Radio.Group
          value={activeTab}
          onChange={e => setActiveTab(e.target.value)}
          buttonStyle="solid"
        >
          <Radio.Button value="overview">
            <DashboardOutlined /> Overview
          </Radio.Button>
          <Radio.Button value="monitoring">
            <LineChartOutlined /> Monitoring
          </Radio.Button>
          <Radio.Button value="alerts">
            <AlertOutlined /> Alerts
          </Radio.Button>
        </Radio.Group>
      ),
    });

    return () => setPageHeader(null);
  }, [setPageHeader, activeTab]);

  const servicesOnline = status
    ? Object.values(status).filter((s: ServiceStatus) => s.online).length
    : 0;
  const allOffline = servicesOnline === 0;

  const renderOverviewTab = () => (
    <>
      {allOffline && (
        <Alert
          message="Monitoring services are offline"
          description={
            <>
              Start monitoring services with: <code>docker compose --profile monitoring up -d</code>
            </>
          }
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}

      {/* Service Status Cards */}
      <Card title="Service Status" style={{ marginBottom: 16 }}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Prometheus"
              online={status?.prometheus?.online || false}
              url={status?.prometheus?.url || ''}
              icon={<DashboardOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Grafana"
              online={status?.grafana?.online || false}
              url={status?.grafana?.url || ''}
              icon={<LineChartOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Alertmanager"
              online={status?.alertmanager?.online || false}
              url={status?.alertmanager?.url || ''}
              icon={<AlertOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="cAdvisor"
              online={status?.cadvisor?.online || false}
              url={status?.cadvisor?.url || ''}
              icon={<DashboardOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Node Exporter"
              online={status?.nodeExporter?.online || false}
              url={status?.nodeExporter?.url || ''}
              icon={<DashboardOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Redis Exporter"
              online={status?.redisExporter?.online || false}
              url={status?.redisExporter?.url || ''}
              icon={<DashboardOutlined />}
            />
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <ServiceStatusCard
              name="Gotify"
              online={status?.gotify?.online || false}
              url={status?.gotify?.url || ''}
              icon={<AlertOutlined />}
            />
          </Col>
        </Row>
      </Card>

      {/* Key Metrics */}
      {!allOffline && <MetricsGrid metrics={metrics} loading={loading} />}

      {/* Active Alerts */}
      {!allOffline && alerts && (
        <AlertsTable alerts={alerts.alerts || []} loading={loading} />
      )}
    </>
  );

  const renderMonitoringTab = () => {
    if (!status?.grafana.online) {
      return (
        <Alert
          message="Grafana is offline"
          description="Start monitoring services to view dashboards"
          type="warning"
          showIcon
        />
      );
    }

    return (
      <IframeErrorBoundary serviceName="Grafana">
        <Card styles={{ body: { padding: 0 } }}>
          {grafanaIframeSrc ? (
            <iframe
              src={grafanaIframeSrc}
              style={{
                width: '100%',
                height: 'calc(100vh - 200px)',
                border: 'none',
              }}
              title="Grafana Dashboard"
              aria-label="Embedded Grafana application overview dashboard"
              sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
              referrerPolicy="strict-origin-when-cross-origin"
              loading="lazy"
            />
          ) : (
            <Spin />
          )}
        </Card>
      </IframeErrorBoundary>
    );
  };

  const renderAlertsTab = () => {
    if (!status?.alertmanager.online) {
      return (
        <Alert
          message="Alertmanager is offline"
          description="Start monitoring services to manage alerts"
          type="warning"
          showIcon
        />
      );
    }

    return (
      <IframeErrorBoundary serviceName="Alertmanager">
        <Card styles={{ body: { padding: 0 } }}>
          {alertmanagerIframeSrc ? (
            <iframe
              src={alertmanagerIframeSrc}
              style={{
                width: '100%',
                height: 'calc(100vh - 200px)',
                border: 'none',
              }}
              title="Alertmanager"
              aria-label="Embedded Alertmanager alert management interface"
              sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
              referrerPolicy="strict-origin-when-cross-origin"
              loading="lazy"
            />
          ) : (
            <Spin />
          )}
        </Card>
      </IframeErrorBoundary>
    );
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '48px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
        <Space>
          <Button icon={<ReloadOutlined />} onClick={fetchAll} loading={loading}>
            Refresh
          </Button>
          {status?.grafana.online && (
            <Button
              type="primary"
              icon={<LinkOutlined />}
              href={status.grafana.url}
              target="_blank"
            >
              Open Grafana
            </Button>
          )}
        </Space>
      </div>
      {activeTab === 'overview' && renderOverviewTab()}
      {activeTab === 'monitoring' && renderMonitoringTab()}
      {activeTab === 'alerts' && renderAlertsTab()}
    </>
  );
}
