import { useCallback, useEffect, useMemo, useState } from 'react';
import { getRemovableDrives } from '@/lib/api/syncfs';
import type { RemovableDrive } from '@/features/deviceSync/utils/deviceSyncHelpers';

export interface DeviceSyncDrivesResult {
  drives: RemovableDrive[];
  drivesLoading: boolean;
  activeDrive: RemovableDrive | null;
  driveDetected: boolean;
  refreshDrives: () => Promise<void>;
}

export function useDeviceSyncDrives(targetDir: string | null): DeviceSyncDrivesResult {
  const [drives, setDrives] = useState<RemovableDrive[]>([]);
  const [drivesLoading, setDrivesLoading] = useState(false);

  const refreshDrives = useCallback(async () => {
    setDrivesLoading(true);
    try {
      const result = await getRemovableDrives();
      setDrives(result);
    } catch {
      setDrives([]);
    } finally {
      setDrivesLoading(false);
    }
  }, []);

  // Fetch drives on mount, then poll every 5 seconds
  useEffect(() => {
    // React Compiler set-state-in-effect rule: state set from a timer/animation callback.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    refreshDrives();
    const interval = setInterval(refreshDrives, 5000);
    return () => clearInterval(interval);
  }, [refreshDrives]);

  // Detect if the current targetDir is on a detected removable drive
  const activeDrive = useMemo(() => {
    if (!targetDir) return null;
    return drives.find(d => targetDir.startsWith(d.mount_point)) ?? null;
  }, [targetDir, drives]);

  const driveDetected = activeDrive !== null;

  return { drives, drivesLoading, activeDrive, driveDetected, refreshDrives };
}
