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"
import useStatus, { useStatusLabel } from "@/utils/useStatus"

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

  const form = useForm({
    budget_detail_id: '',
    vendor_id: '',
    attachment: '',
    amount: '',
    max_amount: maxAmount,
    name: '',
    description: '',
    price: '',
    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 handleBudgetDetailChange = (e) => {
    const budgetDetailOption = props.budget_details?.find(bd => bd.value == e.value)
    const detail = budgetDetailOption?.data

    if (detail) {
      setData((state) => ({
        ...state,
        budget_detail_id: e.value,
        name: detail.name || '',
        description: detail.description || '',
        price: detail.price || '',
        quantity_unit: detail.quantity_unit || [],
        amount: detail.price_total || '',
      }))
    } else {
      setData((state) => ({
        ...state,
        budget_detail_id: e.value,
      }))
    }
  }

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

  return (
    <AuthenticatedLayout title={title} Breadcrumb={Breadcrumb}>
      <div className="bg-white p-4 rounded-lg shadow-sm border mb-4">
        <div className="flex flex-col sm:flex-row justify-between items-start">
          <div>
            <h2 className="font-bold text-lg text-gray-800">{budget.name}</h2>
            <div className="flex items-center gap-2 mb-2">
              {budget.type && <span className={`badge badge-sm ${useStatus(`budget.type.${budget.type}`)}`}>{useStatusLabel(`budget.type.${budget.type}`)}</span>}
              <span className="text-sm text-gray-500">&bull;</span>
            </div>

            <div className="flex flex-wrap gap-x-6 gap-y-2">
              <div className="flex flex-col">
                <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Total Anggaran</span>
                <span className="font-bold text-gray-700">{currency(budget.remaining_amount)}</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">Sudah Dibayar</span>
                <span className="font-bold text-green-600">{currency(budget.paid_amount)}</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">Pembayaran Pending</span>
                <span className="font-bold text-yellow-600">{currency(budget.pending_payment_amount)}</span>
              </div>
            </div>
          </div>
          <div className="text-right w-full sm:w-max">
            <span className="text-xs text-gray-500 block">Sisa Anggaran</span>
            <span className="font-bold text-primary text-xl">
              {currency(maxAmount)}
            </span>
          </div>
        </div>
      </div>

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

        <div className="mt-6 mx-auto flex justify-end gap-2">
          <Link type="button" href={`/admin/budgets`} 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>
              Ajukan Purchase Order
            </span>
          </ModalButton>
        </div>

      </div>

      <ConfirmationModal
        id="confirmation_modal"
        action={pendingAction}
        form={form}
        budget={budget}
        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, handleBudgetDetailChange } = state

  const properties = [
    [
      {
        form: "select",
        props: {
          name: "budget_detail_id",
          label: "Detail Anggaran",
          options: props.budget_details,
          isReactSelect: true,
          isVirtualized: true,
          placeholder: "Pilih Detail Anggaran",
          handleChange: (e) => handleBudgetDetailChange(e),
        }
      },
      {
        form: "select",
        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: 'Dokumen PO:',
        previewClassName: "w-[160px] h-[160px] object-cover border rounded-md",
        props: {
          name: 'attachment',
          label: 'Dokumen Purchase Order',
          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",
        isHidden: !data.budget_detail_id,
        props: {
          name: "name",
          label: "Nama Barang/Jasa",
          type: "text",
          className: 'input input-sm input-bordered',
        },
      },
      {
        form: "input",
        isHidden: !data.budget_detail_id,
        props: {
          name: "price",
          label: "Harga Satuan",
          type: "tel",
          alt: "Rp",
          className: 'input input-sm input-bordered',
        },
      },
    ],
    [
      {
        custom: (formProps) => {
          if (!data.budget_detail_id) return <></>
          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>
          )
        }
      },
      {
        isHidden: !data.budget_detail_id,
        form: "textarea",
        props: {
          type: "text",
          name: "description",
          label: "Keterangan",
          heightClassName: "h-[4.6rem]"
        }
      }
    ],
    [
      {
        isHidden: !data.budget_detail_id,
        form: "input",
        props: {
          name: "amount",
          label: "Total Purchase Order",
          type: "currency",
          bottomLabel: "Total PO terisi otomatis dari kuantitas dan harga satuan",
          required: true,
          disabled: true,
        },
      },
    ],
  ]

  return properties
}

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

  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><span className="cursor-default">Purchase Order</span></li>
      </ul>
    </div>
  )
}
