import { Card, CardBody, Input, Tab, Tabs } from '@nextui-org/react'
import { useEffect, useReducer } from 'react'

const reducer = (prevState, nextState) => {
  return { ...prevState, ...nextState }
}

const defaultData = {
  commonData: 'common',
  tabs: [
    {
      id: 1,
      name: 'tab1',
      range: 10,
      maker: 'maker1',
      law: 'law1',
      basis: 'basis1',
    },
    {
      id: 2,
      name: 'tab2',
      range: 20,
      maker: 'maker2',
      law: 'law2',
      basis: 'basis2',
    },
    {
      id: 3,
      name: 'tab3',
      range: 30,
      maker: 'maker3',
      law: 'law3',
      basis: 'basis3',
    },
    {
      id: 4,
      name: 'tab4',
      range: 40,
      maker: 'maker4',
      law: 'law4',
      basis: 'basis4',
    },
  ],
}

export default function SampleReducer() {
  const [sampleState, setSampleState] = useReducer(reducer, defaultData)

  const handleChangeTabsData = (newTab) => {
    const newTabs = sampleState.tabs.map((t) => {
      if (t.id === newTab.id) {
        return newTab
      } else {
        return t
      }
    })
    setSampleState({ tabs: newTabs })
  }

  useEffect(() => {
    console.log('🚀 ~ SampleReducer ~ sampleState:', sampleState)
  }, [sampleState])

  return (
    <>
      <div>공통: {sampleState.commonData}</div>
      <div className="flex w-full flex-col">
        <Tabs aria-label="Options">
          {sampleState.tabs.map((s) => (
            <Tab key={s.id} title={s.name}>
              <Card>
                <CardBody>
                  <div className="flex w-full flex-wrap md:flex-nowrap gap-4">
                    <Input
                      label="range"
                      type="text"
                      value={s.range}
                      onChange={(e) => {
                        handleChangeTabsData({ ...s, range: e.target.value })
                      }}
                    />
                    <Input
                      label="maker"
                      type="text"
                      value={s.maker}
                      onChange={(e) => {
                        handleChangeTabsData({ ...s, maker: e.target.value })
                      }}
                    />
                    <Input
                      label="law"
                      type="text"
                      value={s.law}
                      onChange={(e) => {
                        handleChangeTabsData({ ...s, law: e.target.value })
                      }}
                    />
                    <Input
                      label="basis"
                      type="text"
                      value={s.basis}
                      onChange={(e) => {
                        handleChangeTabsData({ ...s, basis: e.target.value })
                      }}
                    />
                  </div>
                </CardBody>
              </Card>
            </Tab>
          ))}
        </Tabs>
      </div>
    </>
  )
}
