import { usePortfolioProjects } from '@/src/services/PortfolioProjectService';
import { useProjects } from '@/src/services/ProjectService';
import { PortfolioProject, Project } from '@/src/types/project';
import { PortfolioProjectStatus } from '@prisma/client';
import { useState } from 'react';

export function useProjectEditor(
  portfolioId: string,
  initialProjects: PortfolioProject[],
  onUpdate?: (projects: Project[]) => void
) {
  const { projects: existingProjects } = useProjects();
  const { projects: portfolioProjects, mutate: mutatePortfolioProjects } = usePortfolioProjects(portfolioId);

  const [editingProject, setEditingProject] = useState<PortfolioProject | undefined>(undefined);
  const [selectedProject, setSelectedProject] = useState<Project | undefined>(undefined);
  const [editMode, setEditMode] = useState<'add' | 'edit'>('add');

  const availableProjects = existingProjects?.filter(
    (p) => !portfolioProjects.some((pp) => pp.id === p.id && pp.status !== PortfolioProjectStatus.REJECTED)
  );

  const resetEditing = () => {
    setEditingProject(undefined);
    setEditMode('add');
  };

  const defaultProject: PortfolioProject = {
    id: 'placeholder',
    title: '',
    description: '',
    image: '',
    technologies: [],
    url: '',
    gitUrl: '',
    status: PortfolioProjectStatus.PENDING,
    isOwner: true,
    username: '',
    vercelProjectId: null,
  };

  const safeUpdate = (projects: Project[]) => {
    setTimeout(() => onUpdate?.(projects), 0);
  };

  const handleAddNew = () => {
    const existingProject = initialProjects.find((p) => p.id === 'placeholder');
    if (existingProject) {
      safeUpdate(portfolioProjects);
    } else {
      safeUpdate([...initialProjects, defaultProject]);
    }
    setEditingProject(defaultProject);
    setSelectedProject(undefined);
    setEditMode('add');
  };

  const handleSelectExisting = (projectId: string) => {
    const selected = existingProjects?.find((p) => p.id === projectId);
    if (!selected) return;

    setSelectedProject(selected);
  };

  const handleFieldUpdate = (field: keyof Project, value: string) => {
    setEditingProject((prev) => {
      if (!prev) return undefined;

      let parsedValue: unknown = value;
      if (field === 'technologies' && typeof value === 'string') {
        try {
          parsedValue = JSON.parse(value);
        } catch (e) {
          console.error('Failed to parse technologies', e);
          parsedValue = value;
        }
      }

      const updatedProject = { ...prev, [field]: parsedValue };
      const newProjects = [...initialProjects];
      if (editMode === 'edit' && prev.id) {
        const index = newProjects.findIndex((p) => p.id === prev.id);
        if (index !== -1) {
          newProjects[index] = updatedProject;
        }
      } else if (editMode === 'add') {
        const index = newProjects.findIndex((p) => p.id === 'placeholder');
        if (index !== -1) {
          newProjects[index] = updatedProject;
        } else {
          newProjects.push(updatedProject);
        }
      }

      safeUpdate(newProjects);
      return updatedProject;
    });
  };

  const handleEdit = (projectId: string) => {
    const project = portfolioProjects.find((p) => p.id === projectId);
    if (!project) return;

    safeUpdate(portfolioProjects);
    setEditingProject(project);
    setEditMode('edit');
  };

  const handleCancel = () => {
    resetEditing();
    safeUpdate(portfolioProjects);
  };

  return {
    editingProject,
    editMode,
    selectedProject,
    availableProjects,
    setEditingProject,
    setSelectedProject,
    handleAddNew,
    handleSelectExisting,
    handleFieldUpdate,
    handleEdit,
    handleCancel,
    refreshProjects: mutatePortfolioProjects,
  };
}
