import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import { Link, usePage, useForm, router } from "@inertiajs/react"
import { currency, mimeType } from "@/utils/format"
import { ModalButton } from "@/Components/WithModal"
import { useState } from "react"
import ConfirmationModal from "./Modal/ConfirmationModal"
import { FormProperty } from "@/Components/FormBuilder"
import useFormChange from "@/utils/useFormChange"
import CameraModal from "@/Components/Modal/CameraModal"
import VendorFormModal from "@/Pages/Admin/Vendor/Modal/FormModal"
import { useSetAtom } from "jotai"
import { picturePreviewAtom } from "@/atoms"
import Form from "@/Components/Form/Form"

export default function Index(props) {
  const { budgetDetail, title } = usePage().props
  const budget = budgetDetail?.budget

  const form = useForm({
    vendor_id: '',
    attachment: '',
    amount: budgetDetail.price_total,
    name: budgetDetail.name,
    description: budgetDetail.description,
    price: budgetDetail.price,
    quantity_unit: budgetDetail.quantity_unit,
  });

  const { data, setData, post, processing, errors } = form
  const [pendingAction, setPendingAction] = useState(null)
  const [showCamera, setShowCamera] = useState(false)
  const [showVendorModal, setShowVendorModal] = useState(false)
  const setPicture = useSetAtom(picturePreviewAtom)

  const handleCapture = (file) => {
    setData('attachment', file)

    if (file instanceof File) {
      file = URL.createObjectURL(file)
      setPicture(file)
    }
  }

  const handleSubmit = (onClose) => {
    post(props.page.url, {
      onSuccess: () => {
        onClose && onClose()
        setShowCamera(false)
      },
      onError: () => {
        onClose && onClose()
      },
    })
  }

  const handleActionClick = (action) => {
    setPendingAction(action)
  }

  const handleChange = (e) => {
    const { name, value } = useFormChange(e, data);

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

      setData((state) => ({
        ...state,
        [name]: value,
        amount: priceTotal
      }));
      return
    }

    setData((state) => ({
      ...state,
      [name]: value,
    }));
  }

  const inputProps = { data, setData, handleChange, errors }
  const properties = getProperties({ props, data, setData, inputProps, setShowCamera, setShowVendorModal })

  return (
    <AuthenticatedLayout title={title} Breadcrumb={Breadcrumb}>
      <div className="bg-white p-4 rounded-lg shadow-sm border mb-4 w-full max-w-3xl">
        <div className="flex flex-col gap-4">
          <div className="flex flex-col sm:flex-row justify-between items-start">
            <div>
              <h2 className="font-bold text-lg text-gray-800">{budgetDetail.name}</h2>
              <div className="text-xs text-gray-500 mb-3">{budgetDetail.description}</div>

              <div className="flex flex-wrap gap-x-6 gap-y-2 text-sm">
                <div className="flex flex-col">
                  <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Kategori</span>
                  <span className="font-semibold text-gray-700">{budgetDetail.budget_category?.category?.name || '-'}</span>
                </div>
                <div className="flex flex-col border-l pl-4 border-gray-200">
                  <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Harga Satuan</span>
                  <span className="font-semibold text-gray-700">{currency(budgetDetail.price)}</span>
                </div>
                <div className="flex flex-col border-l pl-4 border-gray-200">
                  <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Kuantitas</span>
                  <div className="font-semibold text-gray-700">
                    <ul className="list-disc list-inside">
                      {budgetDetail.quantity_units?.map((qu, idx) => (
                        <li key={idx}>
                          {qu.quantity} {qu.unit_type?.name}
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
                <div className="flex flex-col border-l pl-4 border-gray-200">
                  <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Total Anggaran</span>
                  <span className="font-semibold text-gray-700">{currency(budgetDetail.price_total)}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white rounded shadow-sm p-4 border border-gray-100 mt-4 max-w-3xl">
        <h3 className="font-bold text-gray-700 mb-4 border-b pb-2">Form Pembelian</h3>
        <FormProperty
          properties={properties}
          inputProps={inputProps}
        />

        <div className="mt-6 mx-auto flex justify-end gap-2">
          <Link type="button" href={`/admin/budgets/${budget.id}/budget_details`} className="btn btn-primary btn-outline btn-sm">
            <i className="fas fa-arrow-left"></i>
            Batal
          </Link>
          <ModalButton id="confirmation_modal" onClick={() => handleActionClick('submit')} disabled={processing}>
            <span className="btn btn-primary btn-sm">
              <i className="fas fa-save"></i>
              Simpan Pembelian
            </span>
          </ModalButton>
        </div>

      </div>

      <ConfirmationModal
        id="confirmation_modal"
        action={pendingAction}
        form={form}
        handleSubmit={handleSubmit}
      />

      {showCamera && (
        <CameraModal
          isOpen={showCamera}
          onClose={() => setShowCamera(false)}
          onCapture={handleCapture}
        />
      )}

      {showVendorModal && (
        <VendorFormModal
          isOpen={showVendorModal}
          onClose={() => setShowVendorModal(false)}
          onSuccess={() => {
            setShowVendorModal(false)
            router.reload({
              only: ['vendors'],
              async: false
            })
          }}
        />
      )}

    </AuthenticatedLayout>
  )
}

const getProperties = (state) => {
  const { data, setData, props, setShowCamera, setShowVendorModal, inputProps } = state

  const properties = [
    [
      {
        form: "select",
        isHidden: true,
        props: {
          name: "vendor_id",
          label: "Vendor",
          options: props.vendors,
          isReactSelect: true,
          isVirtualized: true,
          placeholder: "Pilih Vendor",
          handleChange: (e) => setData((state) => ({ ...state, vendor_id: e.value })),
          alt: (
            <ModalButton id="create_vendor_modal" type="button" onClick={() => setShowVendorModal(true)} className="btn btn-xs badge-soft">
              <i className="fas fa-plus"></i>
              Tambah
            </ModalButton>
          )
        }
      },
    ],
    [
      {
        form: 'input',
        imagePreview: true,
        isSidePreview: false,
        previewLabel: 'Bukti Pembayaran:',
        previewClassName: "w-[160px] h-[160px] object-cover border rounded-md",
        props: {
          name: 'attachment',
          label: 'Bukti Pembayaran',
          type: 'file',
          accept: mimeType('image'),
          required: true,
          alt: (
            <ModalButton id="camera_modal" type="button" onClick={() => setShowCamera(true)} className="btn btn-sm badge-soft">
              <i className="fas fa-camera"></i>
              Ambil Foto
            </ModalButton>
          )
        },
      }
    ],
    [
      {
        form: "input",
        props: {
          name: "name",
          label: "Nama Barang/Jasa",
          type: "text",
          className: 'input input-sm input-bordered',
        },
      },
      {
        form: "input",
        props: {
          name: "price",
          label: "Harga Satuan",
          type: "tel",
          alt: "Rp",
          className: 'input input-sm input-bordered',
        },
      },
    ],
    [
      {
        custom: (formProps) => {
          const quantityUnits = Array.isArray(data.quantity_unit) ? data.quantity_unit : []

          const calculateTotal = (units) => {
            const totalQty = units.length > 0
              ? units.reduce((acc, curr) => acc * (parseFloat(curr.quantity) || 1), 1)
              : 0
            const priceTotal = totalQty * (parseFloat(data.price) || 0)

            setData((state) => ({
              ...state,
              quantity_unit: units,
              amount: priceTotal
            }))
          }

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

          return (
            <div className={`col-span-2 w-full max-w-md border p-3 rounded-md bg-white mt-4`}>
              <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={{
                          ...inputProps,
                          data: qu,
                          handleChange: (e) => updateQU(idx, 'quantity', e.target.value),
                        }}
                      />
                      <Form
                        property={{
                          form: "select",
                          props: {
                            isReactSelect: true,
                            isLabel: false,
                            isCreateAble: true,
                            isVirtualized: true,
                            name: "unit_type_id",
                            options: props.unit_types,
                            placeholder: "Satuan",
                            className: "select select-xs join-item w-full"
                          }
                        }}
                        inputProps={{
                          ...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",
          heightClassName: "h-[4.6rem]"
        }
      }
    ],
    [
      {
        form: "input",
        props: {
          name: "amount",
          label: "Total Pembelian",
          type: "currency",
          bottomLabel: "Total pembelian terisi otomatis dari kuantitas dan harga satuan",
          required: true,
          disabled: true,
        },
      },
    ],
  ]

  return properties
}

const Breadcrumb = ({ currentLabel }) => {
  const { props } = usePage()
  const { budgetDetail } = props
  const budget = budgetDetail?.budget

  return (
    <div className='text-sm text-gray-500 breadcrumbs overflow-auto scrollbar-none'>
      <ul>
        <li><Link href='/admin/budgets' className="text-primary hover:underline">Anggaran</Link></li>
        <li><Link href={`/admin/budgets/${budget?.id}/budget_details`} className="text-primary hover:underline">Detail Anggaran</Link></li>
        <li><span className="cursor-default">Pembelian</span></li>
      </ul>
    </div>
  )
}