"use client";

import { useCallback, useRef, useState } from "react";
import { useSubmitResidenceCard } from "./useResidenceCardVerification";
import type { ResidenceCardVerificationStatus } from "@customer-portal/domain/customer";

interface UseVerificationFileUploadOptions {
  /** Current verification status - upload is disabled when verified */
  verificationStatus?: ResidenceCardVerificationStatus | undefined;
}

/**
 * Hook that encapsulates residence card file upload state and logic.
 * Composes with useSubmitResidenceCard mutation internally.
 */
export function useVerificationFileUpload(options?: UseVerificationFileUploadOptions) {
  const [file, setFile] = useState<File | null>(null);
  const inputRef = useRef<HTMLInputElement | null>(null);
  const submitMutation = useSubmitResidenceCard();

  const canUpload = options?.verificationStatus !== "verified";

  const handleFileChange = useCallback((selectedFile: File | null) => {
    setFile(selectedFile);
  }, []);

  const clearFile = useCallback(() => {
    setFile(null);
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  }, []);

  const submit = useCallback(() => {
    if (!file) return;
    submitMutation.mutate(file, {
      onSuccess: () => {
        setFile(null);
        if (inputRef.current) {
          inputRef.current.value = "";
        }
      },
    });
  }, [file, submitMutation]);

  return {
    /** Currently selected file */
    file,
    /** Ref to attach to the file input element */
    inputRef,
    /** Handler for file input change events */
    handleFileChange,
    /** Clear the selected file and reset the input */
    clearFile,
    /** Submit the selected file for verification */
    submit,
    /** Whether a submission is in progress */
    isSubmitting: submitMutation.isPending,
    /** Whether upload is allowed (not verified) */
    canUpload,
    /** Error from the last submission attempt */
    error: submitMutation.error,
    /** Whether the last submission failed */
    isError: submitMutation.isError,
  };
}
