import axios from 'axios';
import { useRouter } from 'next/router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { toast } from 'react-toastify';
import { logger } from '../../lib/logger';

export type Project = {
  id: string;
  name: string;
};

interface UseProjectSelectorOptions {
  currentUser: unknown;
}

interface UseProjectSelectorReturn {
  projects: Project[];
  selectedProjectId: string;
  isLoadingProjects: boolean;
  selectedProjectName: string;
}

export function useProjectSelector({
  currentUser,
}: UseProjectSelectorOptions): UseProjectSelectorReturn {
  const router = useRouter();

  const routeProjectId = useMemo(() => {
    const value = router.query.projectId;
    if (Array.isArray(value)) return value[0] || '';
    return String(value || '');
  }, [router.query.projectId]);

  const [projects, setProjects] = useState<Project[]>([]);
  const [selectedProjectId, setSelectedProjectId] = useState('');
  const [isLoadingProjects, setIsLoadingProjects] = useState(false);

  const loadProjects = useCallback(async () => {
    setIsLoadingProjects(true);

    try {
      let rows: Project[] = [];
      const response = await axios.get(
        '/projects?limit=100&page=0&sort=desc&field=updatedAt',
      );
      rows = Array.isArray(response?.data?.rows) ? response.data.rows : [];

      if (rows.length === 0) {
        const autocompleteResponse = await axios.get(
          '/projects/autocomplete?limit=100',
        );
        const autocompleteItems = Array.isArray(autocompleteResponse?.data)
          ? autocompleteResponse.data
          : [];
        rows = autocompleteItems.map((item: { id: string; label: string }) => ({
          id: item.id,
          name: item.label,
        }));
      }

      if (rows.length === 0) {
        toast('Please create a project first', {
          type: 'info',
          position: 'bottom-center',
        });
        router.replace('/projects/projects-new');
        return;
      }

      setProjects(rows);

      if (
        routeProjectId &&
        rows.some((project) => project.id === routeProjectId)
      ) {
        setSelectedProjectId(routeProjectId);
      } else {
        setSelectedProjectId((prev) => {
          if (rows.some((project) => project.id === prev)) return prev;
          return rows[0]?.id || '';
        });
      }
    } catch (error: unknown) {
      const errorMessage =
        error instanceof Error ? error.message : String(error);
      logger.error('Failed to load projects:', { error: errorMessage });
      setProjects([]);
      setSelectedProjectId('');
      toast('Failed to load projects', {
        type: 'error',
        position: 'bottom-center',
      });
    } finally {
      setIsLoadingProjects(false);
    }
  }, [routeProjectId, router]);

  useEffect(() => {
    if (!currentUser) return;
    loadProjects();
  }, [routeProjectId, currentUser, loadProjects]);

  const selectedProjectName = useMemo(() => {
    return projects.find((p) => p.id === selectedProjectId)?.name || '';
  }, [projects, selectedProjectId]);

  return {
    projects,
    selectedProjectId,
    isLoadingProjects,
    selectedProjectName,
  };
}

export default useProjectSelector;
