import { useState, useEffect, useCallback, useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import { Button, Space, Badge, Spin, Grid, Result, Alert, Typography } from 'antd';
import { ReloadOutlined, LinkOutlined, LockOutlined, WarningOutlined } 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 VaultwardenPage() {
  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.vaultwarden.online);
      setConfig(configRes.data);
    } catch {
      setOnline(false);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const serviceUrl = config
    ? buildServiceUrl(config.vaultwardenSubdomain, config.domain, config.vaultwardenPort)
    : null;

  // Detect if we're serving via HTTP (localhost/embed port) instead of HTTPS (tunnel)
  const isLocalAccess = !window.location.hostname.includes('.');
  const isHttpAccess = window.location.protocol === 'http:';
  const httpsUrl = config ? `https://${config.vaultwardenSubdomain}.${config.domain}` : 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: 'Password Manager',
      actions: headerActions,
      fullBleed: true
    });
    return () => setPageHeader(null);
  }, [setPageHeader, headerActions]);

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

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

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

  const showHttpWarning = isLocalAccess || isHttpAccess;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 64px)' }}>
      {showHttpWarning && (
        <Alert
          type="warning"
          icon={<WarningOutlined />}
          showIcon
          banner
          message={
            <span>
              <strong>HTTPS required for account creation.</strong>
              {' '}You are accessing Vaultwarden over HTTP (localhost). Browsing an existing vault works,
              but creating accounts or accepting invites requires HTTPS.
              {httpsUrl ? (
                <>
                  {' '}Use your tunnel URL instead:{' '}
                  <Typography.Link href={httpsUrl} target="_blank">{httpsUrl}</Typography.Link>
                </>
              ) : (
                <> Configure a Pangolin tunnel resource for the <code>vault</code> subdomain to enable HTTPS access.</>
              )}
            </span>
          }
          closable
        />
      )}
      <iframe
        src={serviceUrl}
        style={{
          width: '100%',
          flex: 1,
          border: 'none',
          display: 'block',
        }}
        title="Vaultwarden Password Manager"
      />
    </div>
  );
}
