import type { SurveyDetailRequest } from '@/types/Survey'
import { useEffect, useState } from 'react'

export type SelectBoxKeys =
  | 'INSTALLATION_SYSTEM'
  | 'CONSTRUCTION_YEAR'
  | 'ROOF_SHAPE'
  | 'RAFTER_PITCH'
  | 'RAFTER_SIZE'
  | 'OPEN_FIELD_PLATE_KIND'
  | 'STRUCTURE_ORDER'
  | 'INSTALLATION_AVAILABILITY'

const font: Record<SelectBoxKeys, string> = {
  INSTALLATION_SYSTEM: 'data-input-form-tit red-f',
  CONSTRUCTION_YEAR: 'data-input-form-tit red-f',
  ROOF_SHAPE: 'data-input-form-tit',
  RAFTER_PITCH: 'data-input-form-tit red-f',
  RAFTER_SIZE: 'data-input-form-tit red-f',
  OPEN_FIELD_PLATE_KIND: 'data-input-form-tit',
  STRUCTURE_ORDER: 'data-input-form-tit red-f',
  INSTALLATION_AVAILABILITY: 'data-input-form-tit',
}

const translateJapanese: Record<SelectBoxKeys, string> = {
  INSTALLATION_SYSTEM: '設置希望システム',
  CONSTRUCTION_YEAR: '建築年数',
  ROOF_SHAPE: '屋根の形状',
  RAFTER_PITCH: '垂木傾斜',
  RAFTER_SIZE: '垂木サイズ',
  OPEN_FIELD_PLATE_KIND: '路地板の種類',
  STRUCTURE_ORDER: '屋根構造の順序',
  INSTALLATION_AVAILABILITY: '屋根製品名 設置可否確認',
}

export const selectBoxOptions: Record<SelectBoxKeys, { id: number; name: string }[]> = {
  INSTALLATION_SYSTEM: [
    {
      id: 1,
      name: '太陽光発電', //태양광발전
    },
    {
      id: 2,
      name: 'ハイブリッド蓄電システム', //하이브리드축전지시스템
    },
    {
      id: 3,
      name: '蓄電池システム', //축전지시스템
    },
  ],
  CONSTRUCTION_YEAR: [
    {
      id: 1,
      name: '新築', //신축
    },
    {
      id: 2,
      name: '既築', //기존
    },
  ],
  ROOF_SHAPE: [
    {
      id: 1,
      name: '切妻', //박공지붕
    },
    {
      id: 2,
      name: '寄棟', //기동
    },
    {
      id: 3,
      name: '片流れ', //한쪽흐름
    },
  ],
  RAFTER_SIZE: [
    {
      id: 1,
      name: '幅35mm以上×高さ48mm以上',
    },
    {
      id: 2,
      name: '幅36mm以上×高さ46mm以上',
    },
    {
      id: 3,
      name: '幅37mm以上×高さ43mm以上',
    },
    {
      id: 4,
      name: '幅38mm以上×高さ40mm以上',
    },
  ],
  RAFTER_PITCH: [
    {
      id: 1,
      name: '(455mm以下',
    },
    {
      id: 2,
      name: '500mm以下',
    },
    {
      id: 3,
      name: '606mm以下',
    },
  ],
  OPEN_FIELD_PLATE_KIND: [
    {
      id: 1,
      name: '構造用合板', //구조용합판
    },
    {
      id: 2,
      name: 'OSB', //OSB
    },
    {
      id: 3,
      name: 'パーティクルボード', //파티클보드
    },
    {
      id: 4,
      name: '小幅板', //소판
    },
  ],
  STRUCTURE_ORDER: [
    {
      id: 1,
      name: '屋根材', //지붕재
    },
    {
      id: 2,
      name: '防水材', //방수재
    },
    {
      id: 3,
      name: '屋根の基礎', //지붕의기초
    },
    {
      id: 4,
      name: '垂木', //서까래
    },
  ],
  INSTALLATION_AVAILABILITY: [
    {
      id: 1,
      name: '確認済み', //확인완료
    },
    {
      id: 2,
      name: '未確認', //미확인
    },
  ],
}

export default function SelectBoxForm({
  column,
  setDetailInfoData,
  detailInfoData,
}: {
  column: SelectBoxKeys
  setDetailInfoData: (data: any) => void
  detailInfoData: SurveyDetailRequest
}) {
  const [isEtcSelected, setIsEtcSelected] = useState(false)
  const [etcValue, setEtcValue] = useState('')

  useEffect(() => {
    if (detailInfoData[`${column}_ETC` as keyof SurveyDetailRequest]) {
      setIsEtcSelected(true)
      setEtcValue(detailInfoData[`${column}_ETC` as keyof SurveyDetailRequest] as string)
    }
  }, [detailInfoData])

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const value = e.target.value
    const isSpecialCase = column === 'CONSTRUCTION_YEAR' || column === 'INSTALLATION_AVAILABILITY'
    const isEtc = value === 'etc'
    const isSpecialEtc = isSpecialCase && value === '2'

    const updatedData: typeof detailInfoData = {
      ...detailInfoData,
      [column]: isEtc ? null : value,
      [`${column}_ETC`]: isEtc ? '' : null,
    }

    // 건축연수 + 설치가능여부는 2번 선택 시 input 활성화
    if (isSpecialEtc) {
      updatedData[column] = value
    }

    setIsEtcSelected(isEtc || isSpecialEtc)
    if (!isEtc) setEtcValue('')
    setDetailInfoData(updatedData)
  }

  const handleEtcInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setEtcValue(value)
    setDetailInfoData({
      ...detailInfoData,
      [`${column}_ETC`]: value,
    })
  }

  return (
    <>
      <div className="data-input-form-bx">
        <div className={font[column as keyof typeof font]}>{translateJapanese[column as keyof typeof translateJapanese]}</div>
        <div className="data-input mb5">
          <select
            className="select-form"
            name={column}
            id={column}
            onChange={handleSelectChange}
            value={detailInfoData[column] ? detailInfoData[column] : detailInfoData[`${column}_ETC`] ? 'etc' : isEtcSelected ? 'etc' : ''}
          >
            <option value="" hidden>
              選択してください
            </option>
            {selectBoxOptions[column as keyof typeof selectBoxOptions].map((option) => (
              <option key={option.id} value={option.id}>
                {option.name}
              </option>
            ))}
            {column !== 'INSTALLATION_AVAILABILITY' && column !== 'CONSTRUCTION_YEAR' && <option value="etc">その他 (直接入力)</option>}
          </select>
        </div>
        <div className="data-input">
          <input
            type="text"
            className="input-frame"
            value={etcValue ?? ''}
            onChange={handleEtcInputChange}
            disabled={
              column === 'INSTALLATION_AVAILABILITY'
                ? !Boolean(detailInfoData[column])
                : column === 'CONSTRUCTION_YEAR'
                ? detailInfoData[column] !== '2' // 既築(2)가 아닐 때 비활성화
                : !isEtcSelected
            }
          />
        </div>
      </div>
    </>
  )
}
