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

export default function Index(props) {
  const { payment } = props
  const { location, isDirector } = usePage().props

  let maxAmount = payment.max_amount || payment.budget?.paid_remaining_amount || 0
  if (maxAmount > payment.budget?.paid_remaining_amount) {
    maxAmount = payment.budget?.paid_remaining_amount
  }

  const form = useForm({
    user_bank_id: payment.user_bank_id,
    company_bank_id: payment.company_bank_id,
    type: payment.type,
    method: payment.method,
    payment_date: payment.payment_date,
    due_date: payment.due_date,
    cheque_number: payment.cheque_number,
    description: payment.description,
    amount: payment.amount,
    max_amount: maxAmount,
    payment_percentage: payment.payment_percentage || 0,

    status: '',
    status_message: '',
    ref_url: location,
  });

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

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

  useEffect(() => {
    if (data.type === 'full') {
      setData((state) => ({
        ...state,
        amount: data.max_amount || 0,
        max_amount: data.max_amount || 0,
        payment_percentage: 100,
      }))
    }
  }, [data.type])

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

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

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

  const properties = getProperties({ props, data, setData, payment })

  return (
    <AuthenticatedLayout title={props.page.label} Breadcrumb={Breadcrumb}>
      <div className="p-4 bg-white rounded shadow mb-4 flex flex-col md:flex-row justify-between md:items-center sticky top-[57px] z-10 gap-2 md:gap-0">
        <div>
          <h2 className="text-lg font-bold text-gray-800">{payment.code}</h2>
          <p className="text-sm text-gray-500">{dateFormat(payment.payment_date, 'DD MMMM YYYY')}</p>
        </div>
        <div className="flex gap-2">
          <ModalButton id="confirmation_modal" onClick={() => handleActionClick('paid')}>
            <span className="btn btn-primary btn-sm">{isDirector ? 'Proses Pembayaran' : 'Ajukan Pembayaran'}</span>
          </ModalButton>
        </div>
      </div>

      <div className="bg-white rounded shadow-sm p-4 border border-gray-100">
        <h3 className="text-base font-semibold text-gray-800 border-b border-gray-50">Informasi Pembayaran</h3>
        <div className="flex flex-col sm:flex-row justify-between items-start w-full">
          <div>
            <h2 className="font-bold text-lg text-gray-800">{payment.budget?.name || '-'}</h2>
            <div className="flex items-center gap-2 mb-2">
              {payment.budget?.type && <span className={`badge badge-sm ${useStatus(`budget.type.${payment.budget.type}`)}`}>{useStatusLabel(`budget.type.${payment.budget.type}`)}</span>}
              <span className="text-sm text-gray-500">&bull;</span>
              <p className="text-sm text-gray-500">Diajukan pada: {dateFormat(payment.created_at, 'DD MMMM YYYY')}</p>
            </div>

            <div className="flex flex-col md:flex-row flex-wrap justify-between w-full">
              <div className="flex flex-wrap gap-x-6 gap-y-2 mb-4">
                <div className="flex flex-col">
                  <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">User</span>
                  <span className="font-bold text-gray-700">{payment.budget?.user?.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">Departemen</span>
                  <span className="font-bold text-gray-700">{payment.department?.name || '-'}</span>
                </div>
                {(payment.budget?.user?.email) && (
                  <div className="flex flex-col border-l pl-4 border-gray-200">
                    <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">Email</span>
                    <span className="font-bold text-gray-700">{payment.budget?.user?.email}</span>
                  </div>
                )}
                {(payment.budget?.user?.phone) && (
                  <div className="flex flex-col border-l pl-4 border-gray-200">
                    <span className="text-[10px] uppercase text-gray-400 font-bold tracking-wider">WhatsApp</span>
                    <span className="font-bold text-gray-700">{payment.budget?.user?.phone}</span>
                  </div>
                )}
              </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(payment.budget?.remaining_amount || 0)}</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(payment.budget?.paid_amount || 0)}</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(payment.budget?.pending_payment_amount || 0)}</span>
                </div>
              </div>
            </div>
          </div>
          <div className="text-right w-full sm:w-max mt-4 sm:mt-0">
            <span className="text-xs text-gray-500 block">Sisa Anggaran</span>
            <span className="font-bold text-primary text-xl">
              {currency(payment.budget?.paid_remaining_amount || 0)}
            </span>
          </div>
        </div>
      </div>

      <div className="bg-white rounded shadow-sm p-4 border border-gray-100">
        <FormProperty
          properties={properties}
          inputProps={{
            data,
            setData,
            handleChange,
            errors: errors
          }}
        />
      </div>

      <ConfirmationModal
        id="confirmation_modal"
        action={pendingAction}
        remaining={payment.budget?.paid_remaining_amount || 0}
        form={form}
        handleSubmit={handleSubmit}
      />

    </AuthenticatedLayout >
  )
}

const getProperties = (state) => {
  const { props, data, setData, payment } = state

  const properties = [
    [
      {
        form: "select",
        props: {
          name: "method",
          label: "Metode Pembayaran",
          placeholder: "Pilih Metode",
          options: props.methods,
          prefix: "payment.method"
        },
      },
      {
        form: "input",
        isHidden: !['cheque_giro'].includes(data.method),
        props: {
          name: "cheque_number",
          label: "Nomor Cek / Giro",
          placeholder: "Masukan Nomor Cek (jika ada)",
          className: "input input-bordered w-full",
        },
      },
      {
        form: "input",
        props: {
          name: "amount",
          label: "Nominal Pembayaran",
          required: true,
          type: "currency",
          placeholder: "Masukan Nominal Pembayaran",
          className: "input input-bordered w-full",
          disabled: true,
        },
      },

    ],
    [
      {
        form: "select",
        props: {
          isReactSelect: true,
          isVirtualized: true,
          name: "company_bank_id",
          label: "Rekening Asal (Perusahaan)",
          placeholder: "Pilih Rekening Asal (Perusahaan)",
          options: props.company_banks,
          handleChange: (e) => handleSelectReload({ e, name: "company_bank_id", setData })
        },
      },
      {
        form: "select",
        props: {
          isReactSelect: true,
          isVirtualized: true,
          name: "user_bank_id",
          label: "Rekening Tujuan",
          placeholder: "Pilih Rekening Tujuan",
          options: props.user_banks,
          handleChange: (e) => handleSelectReload({ e, name: "user_bank_id", setData })
        },
      },
    ],
    [
      {
        form: "DatePicker",
        props: {
          name: "payment_date",
          label: "Tanggal Pembayaran",
        },
      },
      {
        form: "DatePicker",
        props: {
          name: "due_date",
          label: "Jatuh Tempo",
        },
      },
      {
        form: "textarea",
        props: {
          name: "description",
          label: "Keterangan",
          placeholder: "Keterangan pembayaran...",
          className: "textarea textarea-bordered h-24",
        },
      },
    ],
    [
      {
        custom: () => {
          if (!props.isDirector) return null

          return (
            <div>
              <p>
                Lengkapi form dibawah ini untuk menyelesaikan pembayaran
              </p>
            </div>
          )
        }
      }
    ],
    [
      {
        form: 'input',
        isHidden: !props.isDirector,
        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,
        },
      },
      {
        form: "select",
        isHidden: !props.isDirector,
        props: {
          name: "type",
          label: "Tipe Pembayaran",
          placeholder: "Pilih Tipe",
          options: props.types,
          prefix: "payment.type"
        },
      },
      {
        custom: () => {
          if (data.type !== 'partial' || !props.isDirector) return null

          const maxAmount = data.max_amount

          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 Partial</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}
                    className="range range-xs range-primary"
                    onChange={(e) => {
                      const val = parseInt(e.target.value) || 0
                      setData(data => ({
                        ...data,
                        amount: val,
                        payment_percentage: Math.round((val / maxAmount) * 100)
                      }))
                    }}
                  />
                  <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}
                      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}
                      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/payments' className="text-primary hover:underline">Pembayaran</Link></li>
        <li>Approval Pembayaran</li>
      </ul>
    </div>
  )
}


