'use client';

import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { s3Keys, S3Status, S3StatusType } from './use-s3-plans';

/**
 * Update status DTO
 */
export interface UpdateStatusDto {
  status: S3StatusType;
  photo?: string;
  note?: string;
}

/**
 * Update a status entry
 */
async function updateStatus(
  id: string,
  dto: UpdateStatusDto,
): Promise<S3Status> {
  return api.put(`/lean/s3/status/${id}`, dto);
}

/**
 * Upload a photo for a status entry
 */
async function uploadStatusPhoto(
  id: string,
  file: File,
): Promise<S3Status> {
  const formData = new FormData();
  formData.append('photo', file);

  const response = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api'}/lean/s3/status/${id}/photo`,
    {
      method: 'POST',
      body: formData,
      credentials: 'include',
    },
  );

  if (!response.ok) {
    throw new Error('Failed to upload photo');
  }

  return response.json();
}

/**
 * Hook to update a status entry
 */
export function useUpdateStatus() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateStatusDto }) =>
      updateStatus(id, dto),
    onSuccess: () => {
      // Invalidate all plan queries to refresh the data
      queryClient.invalidateQueries({ queryKey: s3Keys.plans() });
    },
  });
}

/**
 * Hook to upload a photo for a status entry
 */
export function useUploadStatusPhoto() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, file }: { id: string; file: File }) =>
      uploadStatusPhoto(id, file),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: s3Keys.plans() });
    },
  });
}

/**
 * Utility to get status color class
 */
export function getStatusColor(status: S3StatusType): string {
  switch (status) {
    case 'GREEN':
      return 'bg-green-500';
    case 'YELLOW':
      return 'bg-yellow-500';
    case 'RED':
      return 'bg-red-500';
    case 'NOT_APPLICABLE':
    default:
      return 'bg-gray-300';
  }
}

/**
 * Utility to get status text color class
 */
export function getStatusTextColor(status: S3StatusType): string {
  switch (status) {
    case 'GREEN':
      return 'text-green-600';
    case 'YELLOW':
      return 'text-yellow-600';
    case 'RED':
      return 'text-red-600';
    case 'NOT_APPLICABLE':
    default:
      return 'text-gray-500';
  }
}

/**
 * Utility to get next status in workflow
 */
export function getNextStatus(current: S3StatusType): S3StatusType {
  const workflow: S3StatusType[] = [
    'NOT_APPLICABLE',
    'YELLOW',
    'GREEN',
    'RED',
  ];
  const currentIndex = workflow.indexOf(current);
  return workflow[(currentIndex + 1) % workflow.length];
}
