'use client';

import React, { useEffect, useLayoutEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { ArrowLeft, RotateCw } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WizardHeader } from '../headers/WizardHeader';
import { BottomTabBar } from './BottomTabBar';
import { readScroll, saveScroll } from '@/utils/teltoinstall/navigation';

interface Props {
  title: React.ReactNode;
  subtitle?: React.ReactNode;
  /** Affiche une flèche de retour (pages de détail). */
  onBack?: () => void;
  backLabel?: string;
  /** Boutons à droite du titre (ex. actualiser). */
  actions?: React.ReactNode;
  /** Barre d'action fixe au-dessus de la navigation (ex. « Nouvelle installation »). */
  footer?: React.ReactNode;
  /** Navigation Demandes | Historique en bas (pages de premier niveau). */
  showTabs?: boolean;
  /**
   * Le contenu est chargé : la position de défilement mémorisée pour cette page
   * peut être restaurée (une seule fois par affichage).
   */
  restoreScroll?: boolean;
  /** Largeur maximale du contenu (défaut : pleine largeur). */
  contentClassName?: string;
  children: React.ReactNode;
}

/**
 * Gabarit commun des pages hors wizard : en-tête de l'app, en-tête de page
 * (retour + titre + actions), zone défilante dont la position est mémorisée
 * par page, barre d'action et navigation basse.
 */
export function PageLayout({
  title,
  subtitle,
  onBack,
  backLabel,
  actions,
  footer,
  showTabs = false,
  restoreScroll = false,
  contentClassName = '',
  children,
}: Props) {
  const { t } = useTranslation();
  const pathname = usePathname();
  const scrollRef = useRef<HTMLDivElement>(null);
  const restored = useRef(false);

  // Mémorise la position au fil du défilement, et une dernière fois en quittant
  // la page (valeur gardée en mémoire : l'élément est déjà détaché au démontage).
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    let last = el.scrollTop;
    const onScroll = () => {
      last = el.scrollTop;
      saveScroll(pathname, last);
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      el.removeEventListener('scroll', onScroll);
      if (restored.current) saveScroll(pathname, last);
    };
  }, [pathname]);

  // Restaure la position une fois le contenu affiché (retour depuis un détail).
  useLayoutEffect(() => {
    if (!restoreScroll || restored.current || !scrollRef.current) return;
    restored.current = true;
    const top = readScroll(pathname);
    if (top > 0) scrollRef.current.scrollTop = top;
  }, [restoreScroll, pathname]);

  return (
    <div className="h-screen flex flex-col bg-background">
      <div className="flex-shrink-0">
        <WizardHeader />
        <div className="bg-white border-b border-border px-4 py-3 flex items-center gap-3">
          {onBack && (
            <button
              type="button"
              onClick={onBack}
              aria-label={backLabel ?? t('nav.back')}
              title={backLabel ?? t('nav.back')}
              className="w-9 h-9 -ml-1 shrink-0 flex items-center justify-center rounded-full text-foreground hover:bg-muted active:bg-muted transition-colors"
            >
              <ArrowLeft className="w-5 h-5" />
            </button>
          )}
          <div className="min-w-0 flex-1">
            <h2 className="text-lg font-bold text-foreground leading-tight truncate">{title}</h2>
            {subtitle && <div className="text-sm text-muted-foreground truncate">{subtitle}</div>}
          </div>
          {actions && <div className="flex items-center gap-1 shrink-0">{actions}</div>}
        </div>
      </div>

      <div ref={scrollRef} className="flex-1 overflow-y-auto">
        <div className={`w-full px-4 py-4 ${contentClassName}`}>{children}</div>
      </div>

      {footer && (
        <div className="flex-shrink-0 bg-white border-t border-border px-4 py-3 shadow-lg z-20">
          <div className="max-w-lg mx-auto">{footer}</div>
        </div>
      )}
      {showTabs && <BottomTabBar />}
    </div>
  );
}

/** Bouton rond d'actualisation pour la zone `actions` de PageLayout. */
export function RefreshButton({ onClick, spinning }: { onClick: () => void; spinning?: boolean }) {
  const { t } = useTranslation();
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={spinning}
      aria-label={t('nav.refresh')}
      title={t('nav.refresh')}
      className="w-9 h-9 flex items-center justify-center rounded-full border border-border text-primary hover:bg-primary/5 disabled:opacity-60 transition-colors"
    >
      <RotateCw className={`w-4 h-4 ${spinning ? 'animate-spin' : ''}`} />
    </button>
  );
}
