import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import type { HexagonLocation } from '../../lib/external-search';
import { apiUrl, logNonAbortError } from '../../lib/api';
import { CloseIcon, ExpandIcon } from '../ui/icons';

interface StreetViewEmbedProps {
  location: HexagonLocation;
}

type Status = 'loading' | 'ok' | 'none' | 'error';

export default function StreetViewEmbed({ location }: StreetViewEmbedProps) {
  const { t } = useTranslation();
  const [status, setStatus] = useState<Status>('loading');
  const [panoId, setPanoId] = useState<string | null>(null);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    setStatus('loading');
    setPanoId(null);

    const controller = new AbortController();
    const params = new URLSearchParams({
      lat: String(location.lat),
      lon: String(location.lon),
    });

    fetch(apiUrl('streetview', params), { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((data: { status: string; pano_id?: string }) => {
        if (data.status === 'OK' && data.pano_id) {
          setPanoId(data.pano_id);
          setStatus('ok');
        } else {
          setStatus('none');
        }
      })
      .catch((err) => {
        logNonAbortError('streetview', err);
        if (!controller.signal.aborted) {
          setStatus('error');
        }
      });

    return () => controller.abort();
  }, [location.lat, location.lon]);

  useEffect(() => {
    if (!expanded) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setExpanded(false);
      }
    };
    const originalOverflow = document.body.style.overflow;

    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [expanded]);

  if (status === 'none' || status === 'error') return null;

  const panoUrl = panoId
    ? `https://maps.google.com/maps?layer=c&panoid=${panoId}&cbp=11,0,0,0,0&output=svembed`
    : null;

  return (
    <div>
      <div className="px-3 py-1.5 text-xs font-bold text-warm-500 bg-warm-50 dark:bg-warm-900 dark:text-warm-400 sticky top-0 flex items-center justify-between">
        <span>{t('streetView.title')}</span>
        {status === 'ok' && panoUrl && (
          <button
            type="button"
            onClick={() => setExpanded(true)}
            title={t('streetView.openLarge')}
            aria-label={t('streetView.openLarge')}
            className="rounded p-1 text-warm-400 hover:bg-warm-100 hover:text-warm-700 dark:text-warm-500 dark:hover:bg-warm-800 dark:hover:text-warm-200"
          >
            <ExpandIcon className="h-3.5 w-3.5" />
          </button>
        )}
      </div>
      <div className="px-3 py-2">
        <div className="rounded overflow-hidden border border-warm-200 dark:border-warm-700">
          {status === 'loading' || !panoUrl ? (
            <div
              className="w-full animate-pulse bg-warm-200 dark:bg-warm-700"
              style={{ height: 240 }}
            />
          ) : (
            <iframe
              title={t('streetView.title')}
              className="w-full"
              style={{ height: 240, border: 0 }}
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              src={panoUrl}
            />
          )}
        </div>
      </div>
      {expanded &&
        panoUrl &&
        createPortal(
          <div
            className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6"
            role="dialog"
            aria-modal="true"
            aria-label={t('streetView.title')}
          >
            <div
              className="absolute inset-0 bg-black/60 dark:bg-black/75"
              aria-hidden="true"
              onMouseDown={() => setExpanded(false)}
            />
            <div className="relative flex h-[86vh] w-full max-w-7xl flex-col overflow-hidden rounded-lg border border-warm-200 bg-white shadow-2xl dark:border-warm-700 dark:bg-warm-900">
              <div className="flex items-center justify-between border-b border-warm-200 px-4 py-3 dark:border-warm-700">
                <h2 className="text-sm font-semibold text-navy-950 dark:text-warm-100">
                  {t('streetView.title')}
                </h2>
                <button
                  type="button"
                  onClick={() => setExpanded(false)}
                  title={t('common.close')}
                  aria-label={t('common.close')}
                  className="rounded p-1 text-warm-400 hover:bg-warm-100 hover:text-warm-700 dark:text-warm-500 dark:hover:bg-warm-800 dark:hover:text-warm-200"
                >
                  <CloseIcon className="h-5 w-5" />
                </button>
              </div>
              <iframe
                title={t('streetView.expandedTitle')}
                className="min-h-0 flex-1"
                style={{ border: 0 }}
                loading="lazy"
                referrerPolicy="no-referrer-when-downgrade"
                src={panoUrl}
              />
            </div>
          </div>,
          document.body
        )}
    </div>
  );
}
