/**
 * 전개도 상세 관리 커스텀 훅
 *
 * BENDING 부품의 전개도 치수 계산 및 관리
 */

import { useState, useCallback, useEffect } from 'react';
import type { BendingDetail } from '@/types/item';
import type { UseFormSetValue } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';

export interface UseBendingDetailsProps {
  initialDetails?: BendingDetail[];
  setValue?: UseFormSetValue<CreateItemFormData>;
}

export function useBendingDetails({ initialDetails = [], setValue }: UseBendingDetailsProps = {}) {
  const [bendingDetails, setBendingDetails] = useState<BendingDetail[]>(initialDetails);
  const [widthSum, setWidthSum] = useState<string>('');

  /**
   * 폭 합계 계산
   */
  const calculateWidthSum = useCallback((details: BendingDetail[]): number => {
    return details.reduce((acc, d) => {
      const calc = d.input + d.elongation;
      return acc + calc;
    }, 0);
  }, []);

  /**
   * 폭 합계 업데이트 (상태 + form setValue)
   */
  const updateWidthSum = useCallback((details: BendingDetail[]) => {
    const totalSum = calculateWidthSum(details);
    const sumStr = totalSum.toFixed(1);
    setWidthSum(sumStr);
    setValue?.('length', sumStr);
  }, [calculateWidthSum, setValue]);

  /**
   * bendingDetails 변경 시 자동 폭 합계 업데이트
   */
  useEffect(() => {
    if (bendingDetails.length > 0) {
      updateWidthSum(bendingDetails);
    }
  }, [bendingDetails, updateWidthSum]);

  /**
   * 새 행 추가
   */
  const addDetail = useCallback(() => {
    const newId = `detail-${Date.now()}`;
    const newRow: BendingDetail = {
      id: newId,
      no: bendingDetails.length + 1,
      input: 0,
      elongation: -1,
      calculated: 0,
      sum: 0,
      shaded: false,
      aAngle: undefined,
    };
    const newDetails = [...bendingDetails, newRow];
    setBendingDetails(newDetails);
    return newRow;
  }, [bendingDetails]);

  /**
   * 행 삭제
   */
  const removeDetail = useCallback((index: number) => {
    const newDetails = bendingDetails
      .filter((_, i) => i !== index)
      .map((d, i) => ({ ...d, no: i + 1 })); // 번호 재정렬
    setBendingDetails(newDetails);
    updateWidthSum(newDetails);
  }, [bendingDetails, updateWidthSum]);

  /**
   * 행 업데이트
   */
  const updateDetail = useCallback((index: number, updates: Partial<BendingDetail>) => {
    const newDetails = [...bendingDetails];
    newDetails[index] = { ...newDetails[index], ...updates };
    setBendingDetails(newDetails);
    updateWidthSum(newDetails);
  }, [bendingDetails, updateWidthSum]);

  /**
   * 입력값 변경
   */
  const updateInput = useCallback((index: number, value: number) => {
    updateDetail(index, { input: isNaN(value) ? 0 : value });
  }, [updateDetail]);

  /**
   * 연신율 변경
   */
  const updateElongation = useCallback((index: number, value: number) => {
    updateDetail(index, { elongation: isNaN(value) ? -1 : value });
  }, [updateDetail]);

  /**
   * 음영 토글
   */
  const toggleShaded = useCallback((index: number) => {
    const detail = bendingDetails[index];
    if (detail) {
      updateDetail(index, { shaded: !detail.shaded });
    }
  }, [bendingDetails, updateDetail]);

  /**
   * A각 변경
   */
  const updateAAngle = useCallback((index: number, value: number | undefined) => {
    updateDetail(index, { aAngle: value });
  }, [updateDetail]);

  /**
   * 특정 행의 계산값 가져오기
   */
  const getCalculatedValue = useCallback((index: number): number => {
    const detail = bendingDetails[index];
    if (!detail) return 0;
    return detail.input + detail.elongation;
  }, [bendingDetails]);

  /**
   * 모든 상세 초기화
   */
  const resetDetails = useCallback(() => {
    setBendingDetails([]);
    setWidthSum('');
    setValue?.('length', '');
  }, [setValue]);

  /**
   * 상세 데이터 설정 (외부에서 초기화 시)
   */
  const setDetails = useCallback((details: BendingDetail[]) => {
    setBendingDetails(details);
    if (details.length > 0) {
      updateWidthSum(details);
    }
  }, [updateWidthSum]);

  return {
    // 상태
    bendingDetails,
    setBendingDetails: setDetails,
    widthSum,
    setWidthSum,

    // 행 조작
    addDetail,
    removeDetail,
    updateDetail,

    // 필드 업데이트
    updateInput,
    updateElongation,
    toggleShaded,
    updateAAngle,

    // 계산
    calculateWidthSum,
    getCalculatedValue,
    updateWidthSum,

    // 유틸리티
    resetDetails,

    // 상태 체크
    hasDetails: bendingDetails.length > 0,
    detailsCount: bendingDetails.length,
  };
}

export type UseBendingDetailsReturn = ReturnType<typeof useBendingDetails>;