'use client'

import { useState, useEffect } from 'react'
import BasicWriteForm from './BasicWriteForm'
import DetailWriteForm from './DetailWriteForm'
import { SurveySalesBasicInfo, SurveySalesDetailInfo } from '@/api/surveySales'
import { useRouter, useSearchParams } from 'next/navigation'
import { useServey } from '@/hooks/useSurvey'

type TabType = 'basic' | 'detail'

const defaultDetailInfoForm: SurveySalesDetailInfo = {
  contract_capacity: null,
  retail_company: null,
  supplementary_facilities: null,
  supplementary_facilities_etc: null,
  installation_system: null,
  installation_system_etc: null,
  construction_year: null,
  construction_year_etc: null,
  roof_material: null,
  roof_material_etc: null,
  roof_shape: null,
  roof_shape_etc: null,
  roof_slope: null,
  house_structure: null,
  house_structure_etc: null,
  rafter_material: null,
  rafter_material_etc: null,
  rafter_size: null,
  rafter_size_etc: null,
  rafter_pitch: null,
  rafter_pitch_etc: null,
  rafter_direction: null,
  open_field_plate_kind: null,
  open_field_plate_kind_etc: null,
  open_field_plate_thickness: null,
  leak_trace: false,
  waterproof_material: null,
  waterproof_material_etc: null,
  structure_order: null,
  structure_order_etc: null,
  insulation_presence: null,
  insulation_presence_etc: null,
  installation_availability: null,
  installation_availability_etc: null,
  memo: null,
}

const defaultBasicInfoForm: SurveySalesBasicInfo = {
  representative: '',
  store: null,
  construction_point: null,
  investigation_date: null,
  building_name: null,
  customer_name: null,
  post_code: null,
  address: null,
  address_detail: null,
  submission_status: false,
}

export default function MainSurveyForm() {
  const searchParams = useSearchParams()

  const id = searchParams.get('id')

  const [activeTab, setActiveTab] = useState<TabType>('basic')

  const handleTabClick = (tab: TabType) => {
    setActiveTab(tab)
  }

  const router = useRouter()
  const { createSurvey, isCreatingSurvey, createSurveyDetail, surveyDetail, updateSurvey } = useServey(Number(id))

  const [detailInfoForm, setDetailInfoForm] = useState<SurveySalesDetailInfo>(defaultDetailInfoForm)
  const [basicInfoData, setBasicInfoData] = useState<SurveySalesBasicInfo>(defaultBasicInfoForm)

  useEffect(() => {
    if (surveyDetail) {
      setBasicInfoData({
        ...defaultBasicInfoForm,
        ...(({ id, ...rest }) => rest)(surveyDetail),
      })
      setDetailInfoForm({
        ...defaultDetailInfoForm,
        ...(surveyDetail.detail_info ? (({ id, basic_info_id, updated_at, ...rest }) => rest)(surveyDetail.detail_info as any) : {}),
      })
    }
  }, [surveyDetail])

  const handleSave = async (isSubmit: boolean = false) => {
    if (id) {
      updateSurvey({
        ...basicInfoData,
        detail_info: detailInfoForm,
        submission_status: isSubmit,
      })
      router.push('/survey-sales')
      return
    }

    const surveyId = await createSurvey(basicInfoData)
    if (surveyId && surveyId !== 0) {
      createSurveyDetail({
        surveyId,
        surveyDetail: detailInfoForm,
      })
      router.push('/survey-sales')
      return
    }
    throw new Error('‼️Survey creation failed')
  }
  if (isCreatingSurvey) {
    return <div>Loading...</div>
  }

  return (
    <div>
      {/* TAB BUTTONS */}
      <div>
        <button
          onClick={() => handleTabClick('basic')}
          className={`flex-1 px-4 py-2 text-center focus:outline-none focus:ring-2 focus:ring-blue-500 
            ${activeTab === 'basic' ? 'border-b-2 border-blue-500 font-semibold text-blue-600' : 'text-gray-500 hover:text-gray-700'}`}
          aria-selected={activeTab === 'basic'}
          role="tab"
        >
          Basic Info
        </button>
        <button
          onClick={() => handleTabClick('detail')}
          className={`flex-1 px-4 py-2 text-center focus:outline-none focus:ring-2 focus:ring-blue-500
            ${activeTab === 'detail' ? 'border-b-2 border-blue-500 font-semibold text-blue-600' : 'text-gray-500 hover:text-gray-700'}`}
          aria-selected={activeTab === 'detail'}
          role="tab"
        >
          Detail Info
        </button>
      </div>

      {/* Tab Content */}
      <div className="mt-6">
        {activeTab === 'basic' && (
          <div className="rounded-lg border p-4">
            <h2 className="text-lg font-semibold">Basic Information</h2>
            <BasicWriteForm basicInfoData={basicInfoData} setBasicInfoData={setBasicInfoData} />
          </div>
        )}
        {activeTab === 'detail' && (
          <div className="rounded-lg border p-4">
            <h2 className="text-lg font-semibold">Detail Information</h2>
            <DetailWriteForm detailInfoForm={detailInfoForm} setDetailInfoForm={setDetailInfoForm} />
          </div>
        )}
      </div>
      <div className="flex justify-start gap-4">
        <button onClick={() => handleSave(false)}>save</button>
        <button onClick={() => handleSave(true)}>submit</button>
        <button onClick={() => router.push('/survey-sales')}>cancel</button>
      </div>
    </div>
  )
}
