import { Link, usePage } from "@inertiajs/react"
import { useMemo } from 'react'
import { UAParser } from 'ua-parser-js'
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout"
import Table from "@/Components/Table"
import { currency, dateFormat, useSearchParams } from "@/utils/format"
import useStatus, { useStatusLabel } from "@/utils/useStatus"
import useLang from "@/utils/useLang"
import { useAtom } from "jotai"
import { showModalAtom } from "@/atoms"
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "@/Components/ui/accordion"

function Index(props) {
  return (
    <AuthenticatedLayout title={props?.title} Breadcrumb={Breadcrumb}>
      <TableIndex />
    </AuthenticatedLayout>
  )
}

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><Link href={props.location} className="hover:underline">Approval Log</Link></li>
      </ul>
    </div>
  )
}

const TableIndex = (tableProps) => {
  let { tableHeader = null } = tableProps

  const { props } = usePage()
  const { budget } = props

  if (!tableHeader) {
    tableHeader = useTableHeader()
  }

  const filterOptions = useFilterOptions()

  const [show, setShow] = useAtom(showModalAtom)
  const handleShow = (data) => {
    setShow(data)
  }

  return (
    <>
      {budget && (
        <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>
              <p className="text-sm text-gray-500">{dateFormat(budget.created_at, 'DD MMMM YYYY')}</p>
            </div>
            <div className="text-right w-full sm:w-max">
              <span className="text-xs text-gray-500 block">Total Anggaran</span>
              <span className="font-bold text-primary text-xl">
                {currency(budget.remaining_amount)}
              </span>
            </div>
          </div>
        </div>
      )}

      <Table
        cardChecbox={false}
        addButton={false}
        filterOptions={filterOptions}
        tableHeader={tableHeader}
        tableBody={props?.[props?.page?.name]?.data ?? []}
        tableRender={TableRender}
        {...tableProps}
      />

      {show ? (<>  </>) : null}
    </>
  )
}

const TableRender = (props) => {
  const { tableBody } = props

  return (
    <div className="flex flex-col w-full md:max-w-5xl mr-auto py-4 px-2">
      {tableBody.map((item, index) => {
        const isLast = index === tableBody.length - 1

        let parser = new UAParser(item.user_agent);
        let device = parser.getResult();

        const referenceUrl = useMemo(() => {
          if (item.module_type === 'budget' && item.budget?.code) {
            const q = encodeURIComponent(encodeURIComponent(item.budget.code))
            return `/admin/budgets?q=${q}&searchBy=code`
          }
          if (item.module_type === 'payment' && item.payment?.code && item.budget?.id) {
            const code = `\t${item.payment.code}\t`
            const q = encodeURIComponent(encodeURIComponent(code))
            return `/admin/budgets/${item.budget.id}/payment_details?q=${q}&searchBy=code`
          }
          return null
        }, [item])

        return (
          <div key={index} className="flex gap-4">
            {/* Left: Date & Time */}
            <div className="flex flex-col items-end w-auto sm:w-32 pt-1 text-right shrink-0">
              <span className="text-sm font-semibold text-gray-700">
                {dateFormat(item.created_at, 'ddd, DD MMM YYYY')}
              </span>
              <span className="text-xs text-gray-500">
                {dateFormat(item.created_at, 'HH:mm')}
              </span>
              {item.ip_address && (
                <div className="flex flex-col items-end mt-2 gap-0.5">
                  <div className="badge badge-xs badge-ghost font-mono text-[10px] text-gray-400 h-5">
                    {item.ip_address}
                  </div>
                  <div className="text-[10px] text-gray-400 max-w-[120px] truncate" title={`${device.os.name} ${device.os.version}`}>
                    {device.os.name} {device.os.version}
                  </div>
                  <div className="text-[10px] text-gray-400 max-w-[120px] truncate" title={`${device.browser.name} ${device.browser.version}`}>
                    {device.browser.name}
                  </div>
                </div>
              )}
            </div>

            {/* Center: Timeline Line & Dot */}
            <div className="relative flex flex-col items-center shrink-0">
              <div className={`w-3 h-3 rounded-full z-10 ${['submit', 'approve'].includes(item.action) ? 'bg-primary' :
                ['reject', 'revise'].includes(item.action) ? 'bg-red-500' : 'bg-gray-400'
                }`} />
              {!isLast && (
                <div className="flex-1 w-0.5 bg-gray-200 -my-1" />
              )}
            </div>

            {/* Right: Content Card */}
            <div className="flex-1 pb-8">
              <div className="bg-white border rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow">
                <div className="flex justify-between items-start mb-3">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 shrink-0">
                      <i className="fas fa-user-circle text-2xl"></i>
                    </div>
                    <div className="flex flex-col">
                      <span className="font-bold text-gray-800 text-sm">{item.user?.name}</span>
                      <span className="text-xs text-gray-500 capitalize">{useLang(item.user?.role)}</span>
                    </div>
                  </div>
                  <div className={`px-2.5 py-1 rounded-md text-xs font-bold uppercase tracking-wide border ${useStatus(`approval_log.action.${item.action}`)}`}>
                    {useStatusLabel(`approval_log.module_type.${item.module_type}`)} {useStatusLabel(`approval_log.action.${item.action}`)}
                  </div>
                </div>

                {item.note && (
                  <div className="mb-3 text-sm text-gray-600 bg-gray-50 border border-gray-100 p-3 rounded-lg flex gap-2 items-start">
                    <i className="fas fa-quote-left text-gray-300 text-xs mt-0.5"></i>
                    <span className="italic">{item.note}</span>
                  </div>
                )}

                {referenceUrl && (
                  <div className="flex items-center gap-2 mb-3 px-3 py-2 bg-blue-50/50 border border-blue-50 rounded-md">
                    <i className="fas fa-link text-blue-400 text-xs"></i>
                    <span className="text-xs text-gray-500">Referensi:</span>
                    <Link href={referenceUrl} className="text-xs font-mono font-medium text-blue-600 hover:text-blue-800 hover:underline truncate">
                      {item.module_type === 'budget' ? item.budget?.code : item.payment?.code}
                    </Link>
                  </div>
                )}

                <div className="flex flex-wrap gap-3 mt-3 pt-3 border-t border-gray-100">
                  <div className="flex items-center gap-1.5 text-xs text-gray-500 bg-gray-50 px-2.5 py-1.5 rounded-full border border-gray-200">
                    <i className="fas fa-shield-alt text-gray-400"></i>
                    <span className="text-gray-400">Level:</span>
                    <span className="font-medium text-gray-700 capitalize">{useLang(item.approval_level ?? item.submit_level ?? '-')}</span>
                  </div>

                  {item.department?.name && (
                    <div className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-full border transition-colors ${item?.department?.is_finance
                      ? "bg-purple-50 text-purple-700 border-purple-200 shadow-sm"
                      : "bg-gray-50 text-gray-500 border-gray-200"
                      }`}>
                      <i className={`fas fa-building ${item?.department?.is_finance ? "text-purple-500" : "text-gray-400"}`}></i>
                      <span className={item?.department?.is_finance ? "text-purple-400" : "text-gray-400"}>{!!item.approval_department_id && item.approval_department_id !== item.department_id ? "Dari Dept:" : "Dept:"}</span>
                      <span className="font-medium">{item.department?.name}</span>
                    </div>
                  )}

                  {item.approval_department?.name && item.approval_department_id !== item.department_id && (
                    <div className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-full border transition-colors ${item?.approval_department?.is_finance
                      ? "bg-purple-50 text-purple-700 border-purple-200 shadow-sm"
                      : "bg-gray-50 text-gray-500 border-gray-200"
                      }`}>
                      <i className={`fas fa-building ${item?.approval_department?.is_finance ? "text-purple-500" : "text-gray-400"}`}></i>
                      <span className={item?.approval_department?.is_finance ? "text-purple-400" : "text-gray-400"}>Ke Dept:</span>
                      <span className="font-medium">{item.approval_department?.name}</span>
                    </div>
                  )}
                </div>

                <LogDetail item={item} />

              </div>
            </div>
          </div>
        )
      })}

      {tableBody.length === 0 && (
        <div className="p-8 text-center text-gray-500 border rounded-lg">
          Belum ada approval log.
        </div>
      )}
    </div>
  )
}

const useTableHeader = () => {
  const { page, isAdmin, location } = usePage().props
  const { params } = useSearchParams(location)

  const header = [
    {
      label: "#",
      value: "id",
      type: "numbering",
    },
    {
      value: "user.name",
      label: "Pengguna",
      isSearchable: true,
    },
    {
      value: "submit_level",
      label: "Level Pengajuan",
      isSearchable: true,
      prefix: "user.role"
    },
    {
      value: "approval_level",
      label: "Level Persetujuan",
      isSearchable: true,
      prefix: "user.role"
    },
    {
      value: "action",
      label: "Aksi",
      isSearchable: true,
      prefix: "approval_log.action",
    },
    {
      value: "created_at",
      label: "Waktu",
      type: "date",
      className: "text-[13px] w-[10%] md:w-[100px] !whitespace-pre",
    },
    {
      label: "Aksi",
      value: "id",
      type: "action",
    },
  ]

  return header
}

const useFilterOptions = () => {
  const { props } = usePage()
  const filterOptions = [
    {
      name: "status",
      data: props?.status ?? [],
      label: "Filter Status",
    },
    {
      name: "deleted_at",
      label: "Filter Data Terhapus",
    },
  ]

  return filterOptions
}

const HeaderProvider = ({ children }) => {
  const header = useTableHeader()
  return children(header)
}

const FilterProvider = ({ children }) => {
  const filterOptions = useFilterOptions()
  return children(filterOptions)
}

Index.Table = TableIndex
Index.HeaderProvider = HeaderProvider
Index.FilterProvider = FilterProvider


const ApprovalLogIndex = Index
export default ApprovalLogIndex

const LogDetail = ({ item }) => {
  if (!item) return null

  let allData = []

  const parentDetail = item.detail
  if (parentDetail) {
    try {
      let data = typeof parentDetail === 'string' ? JSON.parse(parentDetail) : parentDetail
      data = typeof data === 'string' ? JSON.parse(data) : data
      if (Array.isArray(data)) {
        allData = [...allData, ...data]
      } else if (data && typeof data === 'object') {
        allData.push(data)
      }
    } catch (e) {
      console.warn("Failed to parse parent log detail", e)
    }
  }

  if (item.children && Array.isArray(item.children)) {
    item.children.forEach(child => {
      if (child.detail) {
        try {
          let childData = typeof child.detail === 'string' ? JSON.parse(child.detail) : child.detail
          childData = typeof childData === 'string' ? JSON.parse(childData) : childData

          if (Array.isArray(childData)) {
            allData = [...allData, ...childData]
          } else if (childData && typeof childData === 'object') {
            allData.push(childData)
          }
        } catch (e) {
          console.warn("Failed to parse child log detail", e)
        }
      }
    })
  }

  if (allData.length === 0) return null

  return (
    <div className="mt-4 border rounded-lg bg-gray-50 overflow-hidden">
      <Accordion type="single" collapsible>
        <AccordionItem value="details" className="border-none">
          <AccordionTrigger className="px-4 py-3 hover:no-underline hover:bg-gray-100 transition-colors">
            <span className="text-sm font-semibold text-gray-700">Detail Perubahan ({allData.length} item)</span>
          </AccordionTrigger>
          <AccordionContent>
            <div className="p-0 bg-white">
              <Table
                isCardLoadMore={false}
                tableHeader={detailTableHeader}
                tableBody={allData}
                isAction={false}
                addButton={false}
                tableRender={null}
                wrapperClassName="relative w-full overflow-auto"
              />
            </div>
          </AccordionContent>
        </AccordionItem>
      </Accordion>
    </div>
  )
}

const detailTableHeader = [
  { label: "Nama", value: "name", isSearchable: true, },
  { label: "Harga", value: "price", type: "currency", isSearchable: true, },
  {
    label: "Kuantitas",
    value: "quantity_units",
    isSearchable: true,
    isDefaultLabel: true,
    custom: ({ data, defaultClassName }) => {
      if (!data.quantity_units || !Array.isArray(data.quantity_units)) return <td className={defaultClassName.tdBodyClassName}>-</td>
      return (
        <td className={defaultClassName.tdBodyClassName}>
          <ul className="list-disc list-inside">
            {data.quantity_units.map((qu, idx) => (
              <li key={idx}>
                {qu.quantity} {qu.unit_type?.name || qu.unit_type_id || '-'}
              </li>
            ))}
          </ul>
        </td>
      )
    }
  },
  { label: "Total", value: "price_total", type: "currency", isSearchable: true, },
  {
    label: "Status",
    value: "status",
    isSearchable: true,
    isDefaultLabel: true,
    custom: ({ data, defaultClassName }) => {
      return (
        <td className={defaultClassName.tdBodyClassName}>
          <div className="flex flex-col gap-1 items-start">
            {data.status ? (
              <span className={`px-2 py-0.5 rounded text-[10px] font-semibold uppercase ${useStatus(`budget_detail.status.${data.status}`)}`}>
                {useStatusLabel(`budget_detail.status.${data.status}`)}
              </span>
            ) : (
              <span>-</span>
            )}
            {data.status_message && (
              <span className="text-xs text-gray-500 italic">"{data.status_message}"</span>
            )}
          </div>
        </td>
      )
    }
  }
]

