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, ApiOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/components/AppLayout';
import type { ServicesStatus, ServicesConfig } from '@/types/api';
import { buildServiceUrl } from '@/lib/service-url';

export default function N8nPage() {
  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<ServicesStatus>('/services/status'),
        api.get<ServicesConfig>('/services/config'),
      ]);
      setOnline(statusRes.data.n8n.online);
      setConfig(configRes.data);
    } catch {
      setOnline(false);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const serviceUrl = config
    ? buildServiceUrl(config.n8nSubdomain, config.domain, config.n8nPort)
    : 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>
      {serviceUrl && (
        <Button
          icon={<LinkOutlined />}
          href={serviceUrl}
          target="_blank"
          size="small"
        >
          Open in New Tab
        </Button>
      )}
    </Space>
  ), [online, handleRefresh, serviceUrl]);

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

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

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

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

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