'use client';

import { useCallback, useReducer, useRef, type FormEvent } from 'react';
import { submitInterest } from '@/lib/mock/submitInterest';
import {
  emptyInterest,
  validateField,
  validateInterest,
  type InterestErrors,
  type InterestField,
  type InterestValues,
} from '@/lib/validation';

type FormStatus = 'idle' | 'submitting' | 'success' | 'error';

type State = { values: InterestValues; errors: InterestErrors; status: FormStatus };

type Action =
  | { type: 'change'; field: InterestField; value: string | boolean }
  | { type: 'blur'; field: InterestField }
  | { type: 'invalid'; errors: InterestErrors }
  | { type: 'status'; status: FormStatus }
  | { type: 'reset' };

const initial: State = { values: emptyInterest, errors: {}, status: 'idle' };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'change': {
      const values = { ...state.values, [action.field]: action.value };
      // Only re-check a field that is already showing an error, so typing never nags early.
      if (!state.errors[action.field]) return { ...state, values };
      const error = validateField(action.field, values);
      return { ...state, values, errors: { ...state.errors, [action.field]: error } };
    }
    case 'blur': {
      const filled = action.field !== 'consent' && String(state.values[action.field]).trim() !== '';
      if (!filled) return state;
      return { ...state, errors: { ...state.errors, [action.field]: validateField(action.field, state.values) } };
    }
    case 'invalid':
      return { ...state, errors: action.errors, status: 'idle' };
    case 'status':
      return { ...state, status: action.status, errors: action.status === 'submitting' ? {} : state.errors };
    case 'reset':
      return initial;
  }
}

export function useInterestForm() {
  const [state, dispatch] = useReducer(reducer, initial);
  const formRef = useRef<HTMLFormElement>(null);

  const setField = useCallback(
    (field: InterestField, value: string | boolean) => dispatch({ type: 'change', field, value }),
    [],
  );
  const blurField = useCallback((field: InterestField) => dispatch({ type: 'blur', field }), []);
  const reset = useCallback(() => dispatch({ type: 'reset' }), []);

  const submit = useCallback(
    async (event: FormEvent<HTMLFormElement>) => {
      event.preventDefault();
      if (state.status === 'submitting') return;

      const errors = validateInterest(state.values);
      if (Object.keys(errors).length > 0) {
        dispatch({ type: 'invalid', errors });
        requestAnimationFrame(() => formRef.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus());
        return;
      }

      dispatch({ type: 'status', status: 'submitting' });
      try {
        await submitInterest(state.values);
        dispatch({ type: 'status', status: 'success' });
      } catch {
        dispatch({ type: 'status', status: 'error' });
      }
    },
    [state.status, state.values],
  );

  return { ...state, formRef, setField, blurField, submit, reset };
}
