import useFormBuilder from "@/utils/useFormBuilder"
import useLang from "@/utils/useLang"
import FormBuilder, { FormProperty } from "@/Components/FormBuilder"
import { currency, useSearchParams } from "@/utils/format"
import { handleSelectReload } from "@/utils/useFormChange"
import Form from "@/Components/Form/Form"
import { usePage } from "@inertiajs/react"
import BaseForm from "@/Components/Form/BaseForm"

import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "@/Components/ui/accordion";
import { useState } from "react";
import { Table2, LayoutList } from "lucide-react";
import { cn } from "@/lib/utils";
import { isMobile } from "react-device-detect";
function MainForm({ isEdit = false, formOptions = {}, BackButton = null, label = null, onSubmit = null, SubmitButton = null }) {
  const formConfig = { isEdit, getProperties, formOptions, onSubmit }
  const builderProps = useFormBuilder(formConfig)

  return <FormBuilder {...builderProps} BackButton={BackButton} label={label} SubmitButton={SubmitButton} />
}

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

  const properties = [
    [
      {
        form: "input",
        props: {
          name: "name",
          label: "Nama Anggaran",
          type: "text",
          className: 'input input-sm input-bordered',
        },
      },
    ],
    [
      {
        form: "select",
        props: {
          name: "type",
          label: "Jenis Anggaran",
          className: 'select select-sm select-bordered',
          prefix: "budget.type",
          options: (props?.types ?? []),
        },
      },
      {
        form: "input",
        props: {
          name: "date",
          label: "Tanggal",
          type: "date",
          className: 'input input-sm input-bordered',
        },
      },
      {
        form: 'DatePicker',
        props: {
          name: 'year',
          label: 'Tahun Anggaran',
          type: 'year',
          className: 'input input-sm input-bordered',
          handleChange: (e) => handleSelectReload({ e, name: 'year', params, setData }),
        }
      },
      {
        form: "input",
        isHidden: props.isRevision,
        props: {
          name: "amount",
          label: "Jumlah Anggaran",
          type: "currency",
          disabled: true,
          bottomLabel: "Akan terisi otomatis dari Detail Anggaran",
          className: 'input input-sm input-bordered',
        },
      },
    ],
    [
      {
        custom: (props) => <BudgetDetailForm {...props} {...state} />
      },
    ]
  ]

  return properties
}

const BudgetDetailForm = (props) => {
  const { categories, unit_types, isRevision } = usePage().props
  const { data, setData } = props.form
  const [openItems, setOpenItems] = useState(['item-0'])

  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, { category_id: '', items: [] }])
    setOpenItems((prev) => [...prev, `item-${details.length}`])
  }

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

  const addItem = (detailIndex) => {
    const newDetails = [...details]
    const currentItems = newDetails[detailIndex].items || []

    newDetails[detailIndex].items = [...currentItems, {
      name: '',
      quantity_unit: [{ quantity: '', unit_type_id: unit_types[0]?.value }],
      price: '',
      price_total: '',
      description: ''
    }]
    setData('details', newDetails)
  }

  const removeItem = (detailIndex, itemIndex) => {
    const newDetails = [...details]
    newDetails[detailIndex].items = newDetails[detailIndex].items.filter((_, i) => i !== itemIndex)
    calculateTotal(newDetails)
  }

  const updateItemWrapper = (detailIndex, itemIndex, key, value) => {
    const newDetails = [...details]
    const item = { ...newDetails[detailIndex].items[itemIndex], [key]: value }

    // Recalculate total if quantity_unit changed
    if (key === 'quantity_unit') {
      const qUnits = value || []
      const totalQty = qUnits.length > 0
        ? qUnits.reduce((acc, curr) => acc * (parseFloat(curr.quantity) || 1), 1)
        : 0
      item.price_total = totalQty * (parseFloat(item.price) || 0)
    }

    if (key === 'price') {
      const qUnits = item.quantity_unit || []
      const totalQty = qUnits.length > 0
        ? qUnits.reduce((acc, curr) => acc * (parseFloat(curr.quantity) || 1), 1)
        : 0
      item.price_total = totalQty * (parseFloat(value) || 0)
    }

    newDetails[detailIndex].items[itemIndex] = item
    calculateTotal(newDetails)
  }


  const calculateTotal = (currentDetails) => {
    let grandDebit = 0
    currentDetails.forEach(d => {
      let detailTotal = 0;
      (d.items || []).forEach(i => {
        detailTotal += (parseFloat(i.price_total) || 0)
      })
      grandDebit += detailTotal
    })

    props.form.setData({
      ...props.form.data,
      details: currentDetails,
      amount: grandDebit
    })
  }

  return (
    <BaseForm isLabel={false} name='details' errors={props?.form.errors} >
      <div className="flex items-center justify-between mb-4 sticky top-[57px] bg-white/95 backdrop-blur z-30 py-3 border-b shadow-sm">
        <h3 className="text-lg font-semibold">Detail Anggaran</h3>
        <div className="flex items-center gap-2">
          {!isRevision && (
            <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>

      <Accordion type="multiple" value={openItems} onValueChange={setOpenItems} className="flex flex-col gap-6">
        {details.map((detail, index) => (
          <AccordionItem key={index} value={`item-${index}`} className="border px-4 rounded-lg bg-white relative">
            {!isRevision && (
              <div className="absolute top-5 right-12 z-10">
                <button
                  type="button"
                  className="text-red-500 hover:text-red-700 p-1"
                  onClick={(e) => {
                    e.stopPropagation();
                    removeDetail(index);
                  }}
                  title="Hapus Detail"
                >
                  <i className="fas fa-trash"></i>
                </button>
              </div>
            )}
            <AccordionTrigger className="hover:no-underline py-4">
              <div className="flex w-full items-center justify-between gap-4">
                <div className="w-full md:w-1/2 text-left" onClick={(e) => e.stopPropagation()}>
                  <Form property={{
                    form: "select",
                    props: {
                      isReactSelect: true,
                      isCreateAble: !isRevision,
                      isDisabled: isRevision,
                      name: "category_id",
                      label: "Jenis Item",
                      value: detail.category_id,
                      options: categories,
                      bottomLabel: "Pilih kategori anggaran",
                    },
                  }} inputProps={{
                    ...props.inputProps,
                    handleChange: (e) => updateDetail(index, 'category_id', e),
                    data: detail
                  }} />
                </div>
                <div className="text-sm text-gray-400 mr-14 italic hidden md:block text-right">
                  <p>Klik untuk kelola detail ({detail.items?.length || 0} item)</p>
                  {!openItems.includes(`item-${index}`) && (
                    <p className="font-medium text-gray-600">
                      Subtotal: {currency((detail.items || []).reduce((acc, curr) => acc + (parseFloat(curr.price_total) || 0), 0))}
                    </p>
                  )}
                </div>
              </div>
            </AccordionTrigger>
            <AccordionContent className="md:max-h-[500px] overflow-y-auto scrollbar-thin pr-2">
              <BudgetDetailItem
                detail={detail}
                index={index}
                isRevision={isRevision}
                unit_types={unit_types}
                updateItemWrapper={updateItemWrapper}
                addItem={addItem}
                removeItem={removeItem}
                props={props}
              />
            </AccordionContent>
          </AccordionItem>
        ))}
      </Accordion>
      {details.length === 0 && (
        <p className="text-center text-gray-400 py-4">
          {isRevision ? "Tidak ada item yang perlu direvisi." : 'Belum ada detail anggaran. Klik "Tambah Detail" untuk memulai.'}
        </p>
      )}
    </BaseForm>
  )
}

const BudgetDetailItem = ({ detail, index, isRevision, unit_types, updateItemWrapper, addItem, removeItem, props }) => {
  const [isTable, setIsTable] = useState(!isMobile)

  return (
    <div className="pl-4 border-l-2 border-gray-200">
      <div className="flex items-center justify-between mb-2 sticky top-0 z-20 bg-white py-2 border-b">
        <h4 className="text-sm font-medium text-gray-700">Daftar Item</h4>
        <div className="flex items-center gap-2">
          <div className="flex items-center bg-white dark:bg-gray-800 rounded-lg p-1 border border-gray-200 dark:border-gray-700">
            <button
              type="button"
              onClick={() => setIsTable(true)}
              className={cn(
                "p-1.5 rounded-md transition-all duration-200",
                isTable
                  ? "bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm ring-1 ring-black/5"
                  : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
              )}
              title="Tampilan Tabel"
            >
              <Table2 className="w-4 h-4" />
            </button>
            <button
              type="button"
              onClick={() => setIsTable(false)}
              className={cn(
                "p-1.5 rounded-md transition-all duration-200",
                !isTable
                  ? "bg-white dark:bg-gray-600 text-blue-600 dark:text-blue-400 shadow-sm ring-1 ring-black/5"
                  : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
              )}
              title="Tampilan Card"
            >
              <LayoutList className="w-4 h-4" />
            </button>
          </div>
          {!isRevision && (
            <button
              type="button"
              className="btn btn-primary btn-xs px-x rounded-sm btn-outline"
              onClick={() => addItem(index)}
            >
              <i className="fas fa-plus"></i> Tambah Item
            </button>
          )}
        </div>
      </div>

      <div className="flex flex-col gap-3">
        {isTable && detail.items?.length > 0 && (
          <div className="overflow-x-auto">
            <table className="table table-xs w-full">
              <thead>
                <tr>
                  <th className="w-10">No</th>
                  <th className="min-w-[250px]">Nama Barang/Jasa</th>
                  <th className="min-w-[150px]">Harga Satuan</th>
                  <th className="min-w-[150px]">Kuantitas & Satuan</th>
                  <th className="min-w-[300px]">Keterangan</th>
                  <th className="min-w-[100px]">Total</th>
                  <th className="w-10"></th>
                </tr>
              </thead>
              <tbody>
                {detail.items?.map((item, itemIndex) => {
                  const itemState = {
                    props: { ...props, unit_types },
                    data: item,
                    setData: (key, value) => updateItemWrapper(index, itemIndex, key, value,),
                    isTable
                  }
                  const itemProperties = getBudgetDetailProperties(itemState)

                  return (
                    <tr key={itemIndex} className={item.status === 'revision' ? 'bg-purple-50' : ''}>
                      <td className="align-top">{itemIndex + 1}</td>
                      <td className="align-top">
                        <Form
                          property={itemProperties[0][0]}
                          inputProps={{
                            ...props.inputProps,
                            data: item,
                            handleChange: (e) => updateItemWrapper(index, itemIndex, e.target.name, e.target.value),
                          }}
                        />
                      </td>
                      <td className="align-top">
                        <Form
                          property={itemProperties[0][1]}
                          inputProps={{
                            ...props.inputProps,
                            data: item,
                            handleChange: (e) => updateItemWrapper(index, itemIndex, e.target.name, e.target.value),
                          }}
                        />
                      </td>
                      <td className="align-top">
                        {itemProperties[1][0].custom({ ...props, ...itemState })}
                      </td>
                      <td className="align-top">
                        <Form
                          property={itemProperties[1][1]}
                          inputProps={{
                            ...props.inputProps,
                            data: item,
                            handleChange: (e) => updateItemWrapper(index, itemIndex, e.target.name, e.target.value),
                          }}
                        />
                      </td>
                      <td className="font-bold whitespace-nowrap align-top">
                        {currency(item.price_total || 0)}
                      </td>
                      <td className="align-top">
                        {!isRevision && (
                          <button
                            type="button"
                            className="btn btn-ghost btn-sm text-red-500"
                            onClick={() => removeItem(index, itemIndex)}
                          >
                            <i className="fas fa-trash"></i>
                          </button>
                        )}
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}

        {!isTable && detail.items?.map((item, itemIndex) => {
          const itemState = {
            props: { ...props, unit_types },
            data: item,
            setData: (key, value) => updateItemWrapper(index, itemIndex, key, value),
            isTable
          }

          const itemProperties = getBudgetDetailProperties(itemState)

          return (
            <div key={itemIndex} className={`bg-gray-50 p-3 rounded border relative group ${item.status === 'revision' ? 'border-l-4 border-l-purple-500' : ''}`}>
              {!isRevision && (
                <button
                  type="button"
                  className="absolute top-2 right-2 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                  onClick={() => removeItem(index, itemIndex)}
                >
                  <i className="fas fa-times"></i>
                </button>
              )}

              {isRevision && item.status_message && (
                <div className="bg-purple-50 text-purple-700 p-2 mb-2 rounded text-sm italic">
                  <span className="font-bold">Info Revisi:</span> {item.status_message}
                </div>
              )}

              <p className="text-xs font-mono text-gray-400">
                #{itemIndex + 1}
              </p>

              <FormProperty
                props={itemState.props}
                properties={itemProperties}
                isNumbering={true}
                inputProps={{
                  ...props.inputProps,
                  data: item,
                  handleChange: (e) => updateItemWrapper(index, itemIndex, e.target.name, e.target.value),
                  setData: (key, value) => updateItemWrapper(index, itemIndex, key, value)
                }}
              />
              <div className="mt-4 text-left">
                <p className="text-sm font-bold">
                  Total Harga: {currency(item.price_total || 0)}
                </p>
              </div>
            </div>
          )
        })}

        {(!detail.items || detail.items.length === 0) && (
          <p className="text-sm text-gray-400 italic">Belum ada item ditambahkan.</p>
        )}
      </div>

      <div className="mt-4 text-left">
        <p className="text-sm font-medium">
          Subtotal: {currency((detail.items || []).reduce((acc, curr) => acc + (parseFloat(curr.price_total) || 0), 0))}
        </p>
      </div>
    </div>
  )
}

const getBudgetDetailProperties = (state) => {
  const { props, data, setData, isTable } = state

  const properties = [
    [
      {
        form: "input",
        props: {
          name: "name",
          label: "Nama Barang/Jasa",
          isLabel: !isTable,
          type: "text",
          className: 'input input-sm input-bordered',
        },
      },
      {
        form: "input",
        props: {
          name: "price",
          label: "Harga Satuan",
          isLabel: !isTable,
          type: "tel",
          alt: "Rp",
          className: 'input input-sm input-bordered',
        },
      },
    ],
    [
      {
        custom: (formProps) => {
          const quantityUnits = Array.isArray(data.quantity_unit) ? data.quantity_unit : []

          const addQU = () => {
            setData('quantity_unit', [...quantityUnits, { quantity: '', unit_type_id: '' }])
          }
          const removeQU = (idx) => {
            setData('quantity_unit', quantityUnits.filter((_, i) => i !== idx))
          }
          const updateQU = (idx, key, val) => {
            const newQU = [...quantityUnits]
            newQU[idx] = { ...newQU[idx], [key]: val }
            setData('quantity_unit', newQU)
          }

          return (
            <div className={`col-span-2 w-full max-w-md ${isTable ? '' : 'border p-3 rounded-md bg-white mt-4'}`}>
              {!isTable && <label className="block text-sm font-medium text-gray-700 mb-2">Kuantitas & Satuan</label>}
              <div className="space-y-1 w-full">
                {quantityUnits.map((qu, idx) => (
                  <div key={idx} className="flex md:join items-start md:items-center gap-2 w-full md:w-auto">
                    {/* Desktop Remove Button */}
                    <button type="button" onClick={() => removeQU(idx)} className="hidden md:block join-item btn btn-sm btn-error h-[2.3rem]">
                      <i className="fas fa-times"></i>
                    </button>

                    {/* Inputs Wrapper - Joined on Mobile & Desktop */}
                    <div className="join join-vertical md:join-horizontal flex-1 md:contents">
                      <Form
                        property={{
                          form: "input",
                          props: {
                            isLabel: false,
                            name: "quantity",
                            placeHolder: "Jumlah",
                            type: "number",
                            className: "join-item input input-sm input-bordered input-bordered h-[2.3rem] w-full"
                          }
                        }}
                        inputProps={{
                          ...props.inputProps,
                          data: qu,
                          handleChange: (e) => updateQU(idx, 'quantity', e.target.value),
                        }}
                      />
                      <Form
                        property={{
                          form: "select",
                          props: {
                            isReactSelect: true,
                            isLabel: false,
                            isCreateAble: true,
                            name: "unit_type_id",
                            options: props.unit_types,
                            placeholder: "Satuan",
                            className: "select select-xs join-item w-full"
                          }
                        }}
                        inputProps={{
                          ...props.inputProps,
                          data: qu,
                          handleChange: (e) => updateQU(idx, 'unit_type_id', e),
                        }}
                      />
                    </div>

                    {/* Mobile Remove Button */}
                    <button type="button" onClick={() => removeQU(idx)} className="md:hidden btn btn-sm btn-square btn-ghost text-red-500 bg-red-50 border-red-100 hover:bg-red-100 h-[2.3rem] shrink-0">
                      <i className="fas fa-times"></i>
                    </button>
                  </div>
                ))}
              </div>
              <button type="button" onClick={addQU} className="btn btn-xs btn-ghost text-primary">
                + Tambah Satuan
              </button>
            </div>
          )
        }
      },
      {
        form: "textarea",
        props: {
          type: "text",
          name: "description",
          label: "Keterangan",
          isLabel: !isTable,
          heightClassName: "h-[4.6rem]"
        }
      }
    ]
  ]

  return properties
}


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

MainForm.PropertiesProvider = PropertiesProvider

const BudgetMainForm = MainForm
export default BudgetMainForm
