'use client';

import { useEffect, useState } from 'react';
import { InstallationDetail } from '@/models/teltoinstall/_index';
import { InstallationRepository } from '@/repositories/teltoinstall/_index';

export function useInstallationDetail(id: number | null) {
  const [installation, setInstallation] = useState<InstallationDetail | null>(null);
  const [error, setError] = useState<string | null>(null);
  // Tracks which id the stored result belongs to, so a stale response from a
  // previously selected installation is never shown for the current one.
  const [fetchedId, setFetchedId] = useState<number | null>(null);

  useEffect(() => {
    if (id == null) return;
    let active = true;
    InstallationRepository.getDetail(id)
      .then((data) => {
        if (!active) return;
        setInstallation(data);
        setError(null);
        setFetchedId(id);
      })
      .catch(() => {
        if (!active) return;
        setError('history.loadError');
        setFetchedId(id);
      });
    return () => {
      active = false;
    };
  }, [id]);

  const resolved = fetchedId === id;

  return {
    installation: resolved ? installation : null,
    error: resolved ? error : null,
    loading: id != null && !resolved,
  };
}
