import FormBuilder from '@/Components/FormBuilder';
import { useSearchParams } from '@/utils/format';
import useFormBuilder from '@/utils/useFormBuilder';
import useLang from '@/utils/useLang';
import { router, usePage } from '@inertiajs/react';
import BaseForm from "@/Components/Form/BaseForm";
import Form from "@/Components/Form/Form";

function MainForm({ isEdit = false }) {
  const formConfig = { isEdit, getProperties }
  const builderProps = useFormBuilder(formConfig)

  return (
    <FormBuilder {...builderProps} />
  )
}

const getProperties = (state) => {
  const { data, setData, props, isEdit } = state
  const { params } = useSearchParams(props.location)

  const statusOptions = props.status.map((data) => {
    return {
      label: useLang(data),
      value: data,
    }
  })

  const handleSelectReload = (e, name, only) => {
    let newState = {}
    newState[name] = e?.value ?? ''

    if (!newState[name]) {
      newState[name] = e ?? ''
    }

    if (name == 'user_id') {
      newState['members'] = null
    }

    setData((state) => ({ ...state, ...newState }))

    params.set(name, newState[name])
    router.visit(`?${params.toString()}`, {
      method: 'get',
      only: [...only, 'location'],
      preserveState: true,
      async: false
    })
  }

  const properties = [
    [
      {
        form: 'input',
        props: {
          name: 'name',
          label: 'Nama Departemen',
          type: 'text',
        }
      },
      {
        form: 'input',
        isHidden: !isEdit,
        props: {
          name: 'code',
          label: 'Kode Departemen',
          type: 'text',
        }
      },
      {
        form: 'select',
        isHidden: !['president_director'].includes(props?.auth?.user?.role),
        props: {
          isReactSelect: true,
          isVirtualized: true,
          name: 'user_id',
          label: 'Pilih Direktur',
          options: props.directors,
          handleChange: (e) => handleSelectReload(e, 'user_id', ['members', 'managers', 'selected_user']),
        }
      },
      {
        form: 'select',
        props: {
          isReactSelect: true,
          isVirtualized: true,
          name: 'status',
          label: 'Status',
          options: statusOptions,
          handleChange: (e) => setData('status', e?.value),
        }
      },
    ],
    [
      {
        form: 'checkbox',
        props: {
          name: 'is_finance',
          label: 'Departemen Keuangan',
        }
      },
    ],
    [
      {
        custom: (props) => <DetailMemberForm {...props} {...state} />
      },
    ]
  ]

  return properties
}

const DetailMemberForm = (props) => {
  const { members, managers } = usePage().props
  const { data, setData } = props.form

  const details = Array.isArray(data.details) ? data.details : []

  const updateDetail = (index, key, value) => {
    const newDetails = [...details]
    newDetails[index] = { ...newDetails[index], [key]: value }
    setData('details', newDetails)
  }

  const addDetail = () => {
    setData('details', [...details, { manager_id: '', user_id: [] }])
  }

  const removeDetail = (index) => {
    const newDetails = details.filter((_, i) => i !== index)
    setData('details', newDetails)
  }

  return (
    <BaseForm isLabel={false} name='details' errors={props?.form.errors} >
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold">Detail Departemen</h3>
        <button
          type="button"
          className="btn btn-primary btn-xs px-x rounded-sm"
          onClick={addDetail}
        >
          <i className="fas fa-plus"></i> Tambah Detail
        </button>
      </div>

      <div className="flex flex-col gap-6">
        {details.map((detail, index) => {
          return (
            <div key={index} className="border p-4 rounded-lg bg-white relative">
              <button
                type="button"
                className="absolute top-2 right-2 text-red-500 hover:text-red-700 p-1"
                onClick={() => removeDetail(index)}
                title="Hapus Detail"
              >
                <i className="fas fa-trash"></i>
              </button>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-2">
                <Form property={{
                  form: "select",
                  props: {
                    isReactSelect: true,
                    isVirtualized: true,
                    isCreateAble: true,
                    name: "manager_id",
                    label: "Manager",
                    value: detail.manager_id,
                    options: managers,
                  },
                }} inputProps={{
                  ...props.inputProps,
                  handleChange: (e) => updateDetail(index, 'manager_id', e?.value),
                  data: detail
                }} />
                <div className="md:w-full md:col-span-3">
                  <Form property={{
                    form: "select",
                    props: {
                      isReactSelect: true,
                      isVirtualized: true,
                      isCreateAble: true,
                      isMulti: true,
                      name: "user_id",
                      label: "Anggota",
                      value: detail.user_id,
                      defaultValue: detail.user_id,
                      options: members,
                    },
                  }} inputProps={{
                    ...props.inputProps,
                    handleChange: (e) => updateDetail(index, 'user_id', e),
                    data: detail
                  }} />
                </div>
              </div>
            </div>
          )
        })}
      </div>
      {details.length === 0 && (
        <p className="text-center text-gray-400 py-4">Belum ada detail departemen. Klik "Tambah Detail" untuk memulai.</p>
      )}
    </BaseForm>
  )
}

const PropertiesProvider = ({ children }) => {
  return children(getProperties)
}

MainForm.PropertiesProvider = PropertiesProvider

const DepartmentMainForm = MainForm
export default DepartmentMainForm
