import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import { Link, usePage, useForm } from "@inertiajs/react"
import { currency, dateFormat } from "@/utils/format"
import { ModalButton } from "@/Components/WithModal"
import { useState, useEffect } from "react"
import ConfirmationModal from "./Modal/ConfirmationModal"
import { FormProperty } from "@/Components/FormBuilder"
import useFormChange from "@/utils/useFormChange"
import useStatus, { useStatusLabel } from "@/utils/useStatus"

export default function Index(props) {
  const { budget } = usePage().props
  const { location } = usePage().props

  const maxAmount = budget.paid_remaining_amount

  const form = useForm({
    amount: '',
    payment_percentage: 0,
    max_amount: maxAmount,
    note: '',
    ref_url: location,
  });

  const { data, setData, post, processing, errors } = form
  const [pendingAction, setPendingAction] = useState(null)

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

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

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

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

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

  return (
    <AuthenticatedLayout title={props.page.label} 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>
              <p className="text-sm text-gray-500">Diajukan pada: {dateFormat(budget.created_at, 'DD MMMM YYYY')}</p>
            </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-2xl">
        <FormProperty
          properties={properties}
          inputProps={inputProps}
        />

        <div className="mt-4 mx-auto grid justify-end">
          <ModalButton id="confirmation_modal" onClick={() => handleActionClick('submit')} disabled={!data.amount}>
            <span className="btn btn-primary btn-sm">
              Kirim Pengajuan
              <i className="fas fa-arrow-right"></i>
            </span>
          </ModalButton>
        </div>

      </div>

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

    </AuthenticatedLayout>
  )
}

const getProperties = (state) => {
  const { data, setData, budget, inputProps } = state
  const maxAmount = budget.paid_remaining_amount

  const properties = [
    [
      {
        custom: () => {
          return (
            <div className="col-span-2 w-full p-3 bg-white rounded border border-gray-200 shadow-sm">
              <div className="flex justify-between items-end mb-3">
                <div>
                  <label className="text-xs font-bold text-gray-500 uppercase tracking-wide">Nominal Permintaan</label>
                  <div className="text-xs text-gray-400 mt-0.5">Geser slider atau input manual</div>
                </div>
                <div className="text-right">
                  <div className="text-[10px] uppercase font-bold text-gray-400">Batasan Maksimal</div>
                  <div className="font-bold text-sm text-gray-700 font-mono tracking-tight">{currency(maxAmount)}</div>
                </div>
              </div>

              <div className="flex items-center gap-4 bg-gray-50 p-2.5 rounded-lg border border-gray-100">
                <div className="flex-1 pt-1">
                  <input
                    type="range"
                    min={0}
                    max={maxAmount}
                    value={data.amount || 0}
                    disabled={maxAmount <= 0}
                    className="range range-xs range-primary"
                    onChange={(e) => {
                      const val = parseInt(e.target.value) || 0
                      setData(data => ({
                        ...data,
                        amount: val,
                        payment_percentage: maxAmount > 0 ? Math.round((val / maxAmount) * 100) : 0
                      }))
                    }}
                  />
                  <div className="flex justify-between text-[10px] text-gray-400 px-0.5 mt-1 font-mono select-none">
                    <span>0%</span>
                    <span>50%</span>
                    <span>100%</span>
                  </div>
                </div>
                <div className="w-[140px] shrink-0 flex flex-col gap-2">
                  <div className="relative">
                    <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-bold">Rp</span>
                    <input
                      type="number"
                      className="input input-sm input-bordered w-full pl-8 text-right font-mono font-bold text-gray-700 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                      value={data.amount}
                      disabled={maxAmount <= 0}
                      max={maxAmount}
                      onChange={(e) => {
                        let val = parseInt(e.target.value) || 0;
                        if (val > maxAmount) val = maxAmount;
                        setData(data => ({
                          ...data,
                          amount: val,
                          payment_percentage: maxAmount > 0 ? Math.round((val / maxAmount) * 100) : 0
                        }))
                      }}
                    />
                  </div>
                  <div className="relative">
                    <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs font-bold">%</span>
                    <input
                      type="number"
                      className="input input-sm input-bordered w-full pr-8 text-right font-mono font-bold text-gray-400 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/20"
                      value={data.payment_percentage}
                      min={0}
                      max={100}
                      disabled={maxAmount <= 0}
                      onChange={(e) => {
                        let val = parseInt(e.target.value) || 0;
                        if (val > 100) val = 100;
                        setData(data => ({
                          ...data,
                          payment_percentage: val,
                          amount: Math.round((val / 100) * maxAmount)
                        }))
                      }}
                    />
                  </div>
                </div>
              </div>
            </div>
          )
        }
      },
    ]
  ]

  return properties
}

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

  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>Permintaan Pembayaran</li>
      </ul>
    </div>
  )
}


