import { useState, useEffect, useCallback, useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import { Button, Space, Badge, Spin, Grid, Result } from 'antd';
import { ReloadOutlined, LinkOutlined, CodeOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import { buildServiceUrl } from '@/lib/service-url';
import type { AppOutletContext } from '@/components/AppLayout';
import type { DocsStatus, ServicesConfig } from '@/types/api';

export default function CodeEditorPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [online, setOnline] = useState<boolean | null>(null);
  const [config, setConfig] = useState<ServicesConfig | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchStatus = useCallback(async () => {
    try {
      const [statusRes, configRes] = await Promise.all([
        api.get<DocsStatus>('/docs/status'),
        api.get<ServicesConfig>('/services/config'),
      ]);
      setOnline(statusRes.data.codeServer.online);
      setConfig(configRes.data);
    } catch {
      setOnline(false);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const codeServerUrl = config
    ? buildServiceUrl(config.codeServerSubdomain, config.domain, config.codeServerPort)
    : null;

  const handleRefresh = useCallback(() => {
    fetchStatus();
  }, [fetchStatus]);

  const headerActions = useMemo(() => (
    <Space>
      <Badge
        status={online === null ? 'processing' : online ? 'success' : 'error'}
        text={online === null ? 'Checking...' : online ? 'Online' : 'Offline'}
      />
      <Button
        icon={<ReloadOutlined />}
        onClick={handleRefresh}
        size="small"
      >
        Refresh
      </Button>
      {codeServerUrl && (
        <Button
          icon={<LinkOutlined />}
          href={codeServerUrl}
          target="_blank"
          size="small"
        >
          Open in New Tab
        </Button>
      )}
    </Space>
  ), [online, handleRefresh, codeServerUrl]);

  useEffect(() => {
    setPageHeader({ title: 'Code Editor', actions: headerActions, fullBleed: true });
    return () => setPageHeader(null);
  }, [setPageHeader, headerActions]);

  if (isMobile) {
    return (
      <Result
        status="info"
        title="Desktop Required"
        subTitle="The code editor requires a desktop browser with a larger screen."
        icon={<CodeOutlined style={{ fontSize: 48 }} />}
      />
    );
  }

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

  if (!online || !codeServerUrl) {
    return (
      <Result
        status="error"
        title="Code Server Unavailable"
        subTitle="Code Server is not running or could not be reached. Check that the code-server container is started."
        extra={
          <Button type="primary" onClick={handleRefresh}>
            Retry
          </Button>
        }
      />
    );
  }

  return (
    <iframe
      src={codeServerUrl}
      style={{
        width: '100%',
        height: 'calc(100vh - 64px)',
        border: 'none',
        display: 'block',
      }}
      title="Code Server"
    />
  );
}
