import { useState } from 'react'
import { Mode, SurveyDetailInfo, SurveyDetailRequest } from '@/types/Survey'

type RadioEtcKeys = 'houseStructure' | 'rafterMaterial' | 'waterproofMaterial' | 'insulationPresence' | 'rafterDirection' | 'leakTrace'
type SelectBoxKeys =
  | 'installationSystem'
  | 'constructionYear'
  | 'roofShape'
  | 'rafterPitch'
  | 'rafterSize'
  | 'openFieldPlateKind'
  | 'structureOrder'
  | 'installationAvailability'

export const supplementary_facilities = [
  { id: 1, name: 'エコキュート' }, //에코큐트
  { id: 2, name: 'エネパーム' }, //에네팜
  { id: 3, name: '蓄電池システム' }, //축전지시스템
  { id: 4, name: '太陽光発電' }, //태양광발전
]

export const roof_material = [
  { id: 1, name: 'スレート' }, //슬레이트
  { id: 2, name: 'アスファルトシングル' }, //아스팔트 싱글
  { id: 3, name: '瓦' }, //기와
  { id: 4, name: '金属屋根' }, //금속지붕
]

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

export const radioEtcData: Record<RadioEtcKeys, { id: number; label: string }[]> = {
  houseStructure: [
    {
      id: 1,
      label: '木製',
    },
  ],
  rafterMaterial: [
    {
      id: 1,
      label: '木製',
    },
    {
      id: 2,
      label: '強制',
    },
  ],
  waterproofMaterial: [
    {
      id: 1,
      label: 'アスファルト屋根940（22kg以上）',
    },
  ],
  insulationPresence: [
    {
      id: 1,
      label: 'なし',
    },
    {
      id: 2,
      label: 'あり',
    },
  ],
  rafterDirection: [
    {
      id: 1,
      label: '垂直垂木',
    },
    {
      id: 2,
      label: '水平垂木',
    },
  ],
  leakTrace: [
    {
      id: 1,
      label: 'あり',
    },
    {
      id: 2,
      label: 'なし',
    },
  ],
}

export default function RoofForm(props: {
  roofInfo: SurveyDetailRequest | SurveyDetailInfo
  setRoofInfo: (roofInfo: SurveyDetailRequest) => void
  mode: Mode
}) {
  const makeNumArr = (value: string) => {
    return value
      .split(',')
      .map((v) => v.trim())
      .filter((v) => v.length > 0)
  }
  const { roofInfo, setRoofInfo, mode } = props
  const [isFlip, setIsFlip] = useState<boolean>(true)
  return (
    <div className={`sale-detail-toggle-bx ${isFlip ? 'act' : ''}`}>
      <div className="sale-detail-toggle-head" onClick={() => setIsFlip(!isFlip)}>
        <div className="sale-detail-toggle-name">電気 / 屋根情報</div>
        <div className="sale-detail-toggle-btn-wrap">
          <button className="sale-detail-toggle-btn"></button>
        </div>
      </div>
      <div className="sale-detail-toggle-cont">
        <div className="sale-frame">
          {/* 전기 관계 */}
          <div className="sale-roof-title">電気関係</div>
          <div className="data-form-wrap">
            <div className="data-input-form-bx">
              {/* 전기 계약 용량 */}
              <div className="data-input-form-tit">電気契約容量</div>
              <div className="data-input mb5">
                <input type="text" className="input-frame" value={roofInfo?.contractCapacity ?? ''} readOnly={mode === 'READ'} />
              </div>
              {mode === 'READ' && <input type="text" className="input-frame" defaultValue={'10'} readOnly={mode === 'READ'} />}
              {mode !== 'READ' && (
                <div className="data-input">
                  <select className="select-form" name="" id="">
                    <option value="">kVA</option>
                    <option value="">kVA</option>
                    <option value="">kVA</option>
                    <option value="">kVA</option>
                    <option value="">kVA</option>
                  </select>
                </div>
              )}
            </div>
            <div className="data-input-form-bx">
              {/* 전기 소매 회사사 */}
              <div className="data-input-form-tit">電気小売会社</div>
              <input type="text" className="input-frame" value={roofInfo?.retailCompany ?? ''} readOnly={mode === 'READ'} />
            </div>
            <div className="data-input-form-bx">
              {/* 전기 부대 설비 */}
              <div className="data-input-form-tit">
                電気袋設備<span>※複数選択可能</span>
              </div>
              <div className="data-check-wrap">
                {/* <div className="check-form-box">
                  <input type="checkbox" id="ch01" readOnly={mode === 'READ'} />
                  <label htmlFor="ch01">エコキュート</label>
                </div> */}
                {supplementary_facilities.map((item) => (
                  <div className="check-form-box" key={item.id}>
                    <input
                      type="checkbox"
                      id={`${item.id}`}
                      checked={makeNumArr(roofInfo?.supplementaryFacilities ?? '').includes(String(item.id))}
                      readOnly={mode === 'READ'}
                    />
                    <label htmlFor={`${item.id}`}>{item.name}</label>
                  </div>
                ))}
                <div className="check-form-box">
                  <input type="checkbox" id={`supplementaryFacilitiesEtc`} checked={roofInfo?.supplementaryFacilitiesEtc !== null} readOnly />
                  <label htmlFor={`supplementaryFacilitiesEtc`}>その他 (直接入力)</label>
                </div>
              </div>
              <div className="data-input">
                <input type="text" className="input-frame" placeholder="-" readOnly value={roofInfo?.supplementaryFacilitiesEtc ?? ''} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 설치 희망 시스템 */}
              {/* <div className="data-input-form-tit red-f">設置希望システム</div>
              {mode === 'READ' && (
                <div className="data-input">
                  <input type="text" className="input-frame" defaultValue={''} disabled />
                </div>
              )}
              {mode !== 'READ' && (
                <div className="data-input mb5">
                  <select className="select-form" name="" id="">
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                  </select>
                </div>
              )} */}
              <div className="data-input-form-tit">設置希望システム</div>
              <SelectedBox column="installationSystem" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
          </div>
        </div>
        <div className="sale-frame">
          {/* 지붕 관계 */}
          <div className="sale-roof-title">屋根関係</div>
          <div className="data-form-wrap">
            <div className="data-input-form-bx">
              {/* 건축 연수 */}
              <div className="data-input-form-tit red-f">建築研修</div>
              <div className="data-input mb5">
                {/* {mode === 'READ' && <input type="text" className="input-frame" defaultValue={''} disabled />}
                {mode !== 'READ' && (
                  <select className="select-form" name="" id="">
                    <option value="">新築</option>
                    <option value="">新築</option>
                    <option value="">新築</option>
                    <option value="">新築</option>
                    <option value="">新築</option>
                  </select>
                )} */}
                <SelectedBox column="constructionYear" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
              {/* <div className="data-input flex">
                <input type="text" className="input-frame" defaultValue={''} disabled />
                <span>年</span>
              </div> */}
            </div>
            <div className="data-input-form-bx">
              {/* 지붕재 */}
              <div className="data-input-form-tit">
                屋根材<span>※最大2個まで選択可能</span>
              </div>
              <div className="data-check-wrap">
                {roof_material.map((item) => (
                  <div className="check-form-box" key={item.id}>
                    <input type="checkbox" id={`${item.id}`} checked={makeNumArr(roofInfo?.roofMaterial ?? '').includes(String(item.id))} readOnly />
                    <label htmlFor={`${item.id}`}>{item.name}</label>
                  </div>
                ))}
                <div className="check-form-box">
                  <input type="checkbox" id={`roofMaterialEtc`} checked={roofInfo?.roofMaterialEtc !== null} readOnly />
                  <label htmlFor={`roofMaterialEtc`}>その他 (直接入力)</label>
                </div>
              </div>
              <div className="data-input">
                <input type="text" className="input-frame" placeholder="-" readOnly value={roofInfo?.roofMaterialEtc ?? ''} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 지붕 모양 */}
              <div className="data-input-form-tit">建築研修</div>
              <div className="data-input mb5">
                {/* {mode === 'READ' && <input type="text" className="input-frame" defaultValue={''} disabled />}
                {mode !== 'READ' && (
                  <select className="select-form" name="" id="">
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                    <option value="">太陽光発電</option>
                  </select>
                )} */}
                <SelectedBox column="roofShape" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
              <div className="data-input">
                <input type="text" className="input-frame" defaultValue={''} disabled />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 지붕 경사도도 */}
              <div className="data-input-form-tit">屋根の斜面</div>
              <div className="data-input flex">
                <input type="text" className="input-frame" value={roofInfo?.roofSlope ?? ''} readOnly={mode === 'READ'} />
                <span>寸</span>
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 주택구조조 */}
              <div className="data-input-form-tit">住宅構造</div>
              <RadioSelected column="houseStructure" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 서까래 재질 */}
              <div className="data-input-form-tit">垂木材質</div>
              <RadioSelected column="rafterMaterial" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 서까래 크기 */}
              <div className="data-input-form-tit red-f">垂木サイズ</div>
              <div className="data-input mb5">
                <SelectedBox column="rafterSize" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 서까래 피치 */}
              <div className="data-input-form-tit red-f">垂木サイズ</div>
              <div className="data-input mb5">
                <SelectedBox column="rafterPitch" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 서까래 방향 */}
              <div className="data-input-form-tit red-f">垂木の方向</div>
              <div className="data-check-wrap mb0">
                <RadioSelected column="rafterDirection" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 노지판 종류류 */}
              <div className="data-input-form-tit">路地板の種類</div>
              <div className="data-input mb5">
                <SelectedBox column="openFieldPlateKind" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 노지판 두께 */}
              <div className="data-input-form-tit">
                路地板厚<span>※小幅板を選択した場合, 厚さ. 小幅板間の間隔寸法を記載</span>
              </div>
              <div className="data-input flex">
                <input type="text" className="input-frame" value={roofInfo?.openFieldPlateThickness ?? ''} readOnly={mode === 'READ'} />
                <span>mm</span>
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 누수 흔적 */}
              <div className="data-input-form-tit ">水漏れの痕跡</div>
              <div className="data-check-wrap mb0">
                <RadioSelected column="leakTrace" detailInfoData={roofInfo as SurveyDetailInfo} />
              </div>
            </div>
            <div className="data-input-form-bx">
              {/* 방수재 종류 */}
              <div className="data-input-form-tit red-f">防水材の種類</div>
              <RadioSelected column="waterproofMaterial" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 단열재 유무 */}
              <div className="data-input-form-tit red-f">断熱材の有無</div>
              <RadioSelected column="insulationPresence" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 지붕 구조의 순서 */}
              <div className="data-input-form-tit red-f">屋根構造の順序</div>
              <SelectedBox column="structureOrder" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 지붕 제품명 설치 가능 여부 확인 */}
              <div className="data-input-form-tit">屋根製品名 設置可否確認</div>
              <SelectedBox column="installationAvailability" detailInfoData={roofInfo as SurveyDetailInfo} />
            </div>
            <div className="data-input-form-bx">
              {/* 메모 */}
              <div className="data-input-form-tit">メモ</div>
              <div className="data-input">
                <textarea
                  className="textarea-form"
                  name=""
                  id=""
                  placeholder="TextArea Filed"
                  value={roofInfo?.memo ?? ''}
                  readOnly={mode === 'READ'}
                ></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

const SelectedBox = ({ column, detailInfoData }: { column: string; detailInfoData: SurveyDetailInfo }) => {
  const selectedId = detailInfoData?.[column as keyof SurveyDetailInfo]
  const etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]

  return (
    <>
      <select className="select-form mb10" name={column} id={column} disabled value={selectedId ? 'selected' : etcValue ? 'etc' : ''}>
        <option value="">-</option>
        <option value="etc">その他 (直接入力)</option>
        <option value="selected">{selectBoxOptions[column as keyof typeof selectBoxOptions][Number(selectedId)]?.name}</option>
      </select>
      {etcValue && <input type="text" className="input-frame" readOnly value={etcValue.toString()} />}
    </>
  )
}

const RadioSelected = ({ column, detailInfoData }: { column: string; detailInfoData: SurveyDetailInfo | null }) => {
  let selectedId = detailInfoData?.[column as keyof SurveyDetailInfo]
  if (column === 'leakTrace') {
    selectedId = Number(selectedId)
    if (!selectedId) selectedId = 2
  }

  let etcValue = null
  if (column !== 'rafterDirection') {
    etcValue = detailInfoData?.[`${column}Etc` as keyof SurveyDetailInfo]
  }
  const etcChecked = etcValue !== null && etcValue !== undefined && etcValue !== ''

  // console.log('column: selectedId', column, selectedId)
  return (
    <>
      {radioEtcData[column as keyof typeof radioEtcData].map((item) => (
        <div className="radio-form-box mb10" key={item.id}>
          <input type="radio" name={column} id={`${item.id}`} disabled checked={Number(selectedId) === item.id} />
          <label htmlFor={`${item.id}`}>{item.label}</label>
        </div>
      ))}
      {column !== 'rafterDirection' && column !== 'leakTrace' && column !== 'insulationPresence' && (
        <div className="radio-form-box mb10">
          <input type="radio" name={column} id={`${column}Etc`} value="etc" disabled checked={etcChecked} />
          <label htmlFor={`${column}Etc`}>その他 (直接入力)</label>
        </div>
      )}
      {etcChecked && (
        <div className="data-input">
          <input type="text" className="input-frame" placeholder="-" readOnly value={etcValue?.toString() ?? ''} />
        </div>
      )}
    </>
  )
}
