import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import { Link, usePage, useForm } from "@inertiajs/react"
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "@/Components/ui/accordion"
import { currency, dateFormat } from "@/utils/format"
import { ModalButton } from "@/Components/WithModal"
import { useState } from "react"
import useStatus, { useStatusLabel } from "@/utils/useStatus"
import ConfirmationModal from "./Modal/ConfirmationModal"
import Table from "@/Components/Table"

export default function Index(props) {
  const { budget_approvals, budgetCategorySum } = props
  const list = budget_approvals?.data || []

  const { location, budgetDetailRevisions } = usePage().props

  // Initialize open items for all categories
  const [openItems, setOpenItems] = useState(() => {
    if (budgetDetailRevisions && budgetDetailRevisions.length > 0) {
      const indices = []
      list.forEach((cat, index) => {
        const hasRevision = cat.budget_details.some(detail =>
          budgetDetailRevisions.some(rev => rev.id === detail.id)
        )
        if (hasRevision) indices.push(`item-${index}`)
      })
      return indices
    }
    return list.map((_, i) => `item-${i}`)
  })

  const initialFormData = {
    budget_categories: list.map(item => ({
      id: item.id,
      category_id: item.category_id,
      _category_name: item.category?.name,
      _subtotal: item.price_amount_total,
      budget_details: item.budget_details.map(detail => ({
        id: detail.id,
        // Ensure booleans
        is_approved: detail.status == "approved",
        is_rejected: detail.status == "rejected",
        is_revision: detail.status == "revision",
        status_message: detail.status_message,
        // Keep original data for display
        _original: detail
      })) || []
    })),
    custom_note: ''
  }

  const form = useForm({
    ...initialFormData,
    ref_url: location,
  });

  const { data, setData, post, errors } = form

  // Helper to update state
  const updateDetail = (catIndex, detailIndex, field, value) => {
    const newData = { ...data }
    const detail = newData.budget_categories[catIndex].budget_details[detailIndex]

    // Mutually exclusive logic
    if (field === 'is_approved' && value) {
      detail.is_rejected = false;
      detail.is_revision = false;
      detail.status_message = null; // Clear message if approved
    } else if ((field === 'is_rejected' || field === 'is_revision') && value) {
      detail.is_approved = false;
      if (field === 'is_rejected') detail.is_revision = false;
      if (field === 'is_revision') detail.is_rejected = false;
    }

    detail[field] = value
    setData(newData)
  }

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

  const updateAllDetails = (catIndex, field) => {
    const newData = { ...data }
    const category = newData.budget_categories[catIndex]

    category.budget_details.forEach((detail, detailIndex) => {
      // If we are in revision mode, only check items that are in revisions
      if (budgetDetailRevisions && budgetDetailRevisions.length > 0) {
        const isInRevision = budgetDetailRevisions.some(rev => rev.id === detail.id)
        if (!isInRevision) return
      }
      updateDetail(catIndex, detailIndex, field, true)
    })

    setData(newData)
  }

  // Create table header for a specific category index
  const getTableHeader = (catIndex) => [
    { label: "#", value: "id", type: "numbering", isSearchable: true },
    { label: "Nama", value: "_original.name", isSearchable: true },
    { label: "Harga Satuan", value: "_original.price", type: "currency", isSearchable: true },
    {
      label: "Kuantitas",
      value: "_original.quantity_units",
      isSearchable: true,
      isDefaultLabel: true,
      custom: ({ data, key, isTable = true }) => {
        const Tag = isTable ? "td" : "div"
        return (
          <Tag key={key}>
            <ul className={`list-disc list-inside`}>
              {data._original.quantity_units?.map((qu, idx) => (
                <li key={idx}>
                  {qu.quantity} {qu.unit_type.name}
                </li>
              ))}
            </ul>
          </Tag>
        )
      }
    },
    { label: "Total", value: "_original.price_total", type: "currency", isSearchable: true },
    { label: "Keterangan", value: "_original.description", type: "text", isSearchable: true },
    {
      label: "Aksi",
      value: "approval_actions",
      isSearchable: true,
      isDefaultLabel: true,
      custom: ({ data: rowData, rowIndex, defaultClassName }) => {
        const detail = rowData
        if (!detail) return null

        // Check revisions
        if (budgetDetailRevisions && budgetDetailRevisions.length > 0) {
          const isInRevision = budgetDetailRevisions.some(rev => rev.id === detail.id)
          if (!isInRevision) return (
            <td className={`${defaultClassName.tdBodyClassName} text-center text-gray-400 italic text-xs flex flex-col`}>
              <div className={`badge ${useStatus(`budget_detail.status.${detail?._original?.status}`)}`}>
                {useStatusLabel(`budget_detail.status.${detail?._original?.status}`)}
              </div>
              {detail?._original?.status_message && (
                <span className="text-xs text-gray-500 italic">"{detail?._original?.status_message}"</span>
              )}
            </td>
          )
        }

        return (
          <td className={`${defaultClassName.tdBodyClassName}`}>
            <div className=" flex flex-col gap-2">
              <div className="flex gap-4 ">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    className="checkbox checkbox-xs checkbox-success"
                    checked={detail.is_approved || false}
                    onChange={(e) => updateDetail(catIndex, rowIndex, 'is_approved', e.target.checked)}
                  />
                  <span className="text-xs">Setujui</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    className="checkbox checkbox-xs checkbox-warning"
                    checked={detail.is_revision || false}
                    onChange={(e) => updateDetail(catIndex, rowIndex, 'is_revision', e.target.checked)}
                  />
                  <span className="text-xs">Revisi</span>
                </label>
                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    className="checkbox checkbox-xs checkbox-error"
                    checked={detail.is_rejected || false}
                    onChange={(e) => updateDetail(catIndex, rowIndex, 'is_rejected', e.target.checked)}
                  />
                  <span className="text-xs">Tolak</span>
                </label>
              </div>
              {(detail.is_rejected || detail.is_revision) && (
                <textarea
                  className="textarea textarea-bordered textarea-xs w-full"
                  placeholder="Tulis catatan revisi/penolakan jika ada..."
                  value={detail.status_message || ''}
                  onChange={(e) => updateDetail(catIndex, rowIndex, 'status_message', e.target.value)}
                ></textarea>
              )}
              {errors && errors[`budget_categories.${catIndex}.budget_details.${rowIndex}.status_message`] && (
                <span className="text-error text-[10px]">{errors[`budget_categories.${catIndex}.budget_details.${rowIndex}.status_message`]}</span>
              )}
            </div>
          </td>
        )
      }
    }
  ]

  // Calculate totals dynamically based on form data
  const calculatedTotals = data.budget_categories.reduce((acc, category) => {
    const categoryTotal = category.budget_details.reduce((sum, detail) => {
      // If rejected, exclude from total.
      // Assuming initial state includes everything, and we subtract if rejected.
      // Or safer: sum everything that is NOT rejected.
      if (detail.is_rejected) return sum

      return sum + parseFloat(detail._original?.price_total || 0)
    }, 0)

    acc.grandTotal += categoryTotal
    acc.categories[category.category_id] = categoryTotal
    return acc
  }, { grandTotal: 0, categories: {} })

  const budgetCategoryRevisionIds = budgetDetailRevisions.map(detail => detail.budget_category_id)

  return (
    <AuthenticatedLayout title={props.page.label} Breadcrumb={Breadcrumb}>
      <div className="p-4 bg-white rounded shadow mb-4 flex justify-between items-center sticky top-[57px] z-10">
        <div>
          <div>
            <h2 className="font-bold text-lg text-gray-800">{props.budget.name}</h2>
            <div className="flex items-center gap-2 mb-2">
              {props.budget.type && <span className={`badge badge-sm ${useStatus(`budget.type.${props.budget.type}`)}`}>{useStatusLabel(`budget.type.${props.budget.type}`)}</span>}
              <span className="text-sm text-gray-500">&bull;</span>
              <p className="text-sm text-gray-500">{props.budget.code} - {dateFormat(props.budget.created_at, 'DD MMMM YYYY')}</p>
            </div>
          </div>
          <h2 className="text-base mt-2 font-bold">Total Pengajuan: {currency(calculatedTotals.grandTotal)}</h2>
        </div>
        <ModalButton id="confirm_approval">
          <span className="btn btn-primary btn-sm">Simpan Approval</span>
        </ModalButton>
      </div>

      <ConfirmationModal
        id="confirm_approval"
        handleSubmit={handleSubmit}
        processing={form.processing}
        data={data}
        setData={setData}
      />

      <Accordion type="multiple" value={openItems} onValueChange={setOpenItems} className="flex flex-col gap-6">
        {data.budget_categories.map((category, index) => {
          return (
            <AccordionItem key={index} value={`item-${index}`} className="border px-4 rounded-lg bg-white">
              <AccordionTrigger className="hover:no-underline py-4">
                <div className="flex w-full items-center justify-between">
                  <span>{category._category_name || '-'}</span>
                  <span className="mr-4 text-sm text-gray-500">
                    Subtotal: {currency(calculatedTotals.categories[category.category_id] || 0)}
                  </span>
                </div>
              </AccordionTrigger>
              {budgetCategoryRevisionIds?.length == 0 || budgetCategoryRevisionIds.includes(category.id) ? (
                (
                  <div className="flex gap-2 mb-4 px-4 bg-gray-50 p-2 rounded-lg border-t border-b items-center">
                    <button
                      onClick={() => updateAllDetails(index, 'is_approved')}
                      className="btn btn-xs badge-soft bg-green-100 text-green-700 ring-green-200 btn-success gap-1 hover:text-white outline-none border-none"
                    >
                      <i className="fas fa-check"></i> Setujui Semua
                    </button>
                    <button
                      onClick={() => updateAllDetails(index, 'is_revision')}
                      className="btn btn-xs badge-soft bg-yellow-100 text-yellow-700 ring-yellow-200 btn-warning gap-1 hover:text-white outline-none border-none"
                    >
                      <i className="fas fa-edit"></i> Revisi Semua
                    </button>
                    <button
                      onClick={() => updateAllDetails(index, 'is_rejected')}
                      className="btn btn-xs badge-soft bg-red-100 text-red-700 ring-red-200 btn-error gap-1 hover:text-white outline-none border-none"
                    >
                      <i className="fas fa-times"></i> Tolak Semua
                    </button>
                  </div>
                )
              ) : null}
              <AccordionContent>
                <div className="">
                  <Table
                    isCardLoadMore={false}
                    tableHeader={getTableHeader(index)}
                    tableBody={category.budget_details}
                    isAction={false}
                    addButton={false}
                    wrapperClassName="relative w-full flex flex-col items-center"
                  />
                </div>
              </AccordionContent>
            </AccordionItem>
          )
        })}
      </Accordion>
    </AuthenticatedLayout>
  )
}

const Breadcrumb = ({ currentLabel }) => {
  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>Approval Anggaran</li>
      </ul>
    </div>
  )
}


