import { useState, useEffect, useCallback, useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import { Button, Space, Badge, Spin, Grid, Result, Alert } from 'antd';
import { ReloadOutlined, LinkOutlined, DatabaseOutlined } 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';

const BANNER_DISMISSED_KEY = 'nocodb-auth-banner-dismissed';

export default function NocoDBPage() {
  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 [bannerDismissed, setBannerDismissed] = useState(
    () => localStorage.getItem(BANNER_DISMISSED_KEY) === '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.nocodb.online);
      setConfig(configRes.data);
    } catch {
      setOnline(false);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const serviceUrl = config
    ? buildServiceUrl(config.nocodbSubdomain, config.domain, config.nocodbPort)
    : 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: 'Database Browser', actions: headerActions, fullBleed: true });
    return () => setPageHeader(null);
  }, [setPageHeader, headerActions]);

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

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

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

  return (
    <div style={{ height: 'calc(100vh - 64px)', display: 'flex', flexDirection: 'column' }}>
      {!bannerDismissed && (
        <Alert
          message={
            <>
              If the database browser appears blank, you may need to{' '}
              <a href={serviceUrl} target="_blank" rel="noopener noreferrer">
                sign in to NocoDB in a new tab
              </a>{' '}
              first, then refresh this page.
            </>
          }
          type="info"
          showIcon
          closable
          onClose={() => {
            setBannerDismissed(true);
            localStorage.setItem(BANNER_DISMISSED_KEY, 'true');
          }}
          style={{ borderRadius: 0, flexShrink: 0 }}
        />
      )}
      <iframe
        src={serviceUrl}
        style={{
          width: '100%',
          flex: 1,
          border: 'none',
          display: 'block',
        }}
        title="NocoDB"
      />
    </div>
  );
}
