import { Head, router, usePage } from '@inertiajs/react'
import { Main } from '@ui/components/layout/main'
import { Badge } from '@ui/components/ui/badge'
import { Button } from '@ui/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@ui/components/ui/card'
import { Input } from '@ui/components/ui/input'
import { Spinner } from '@ui/components/ui/spinner'
import { useEffect, useMemo, useState } from 'react'
import { FinanceAppLayout } from '@/layouts/finance-app-layout'
import { useAppText } from '@/lib/app-text'

type PaymentHistory = {
  payment_id: number
  nomor_bukti_bayar: string
  jumlah: number
  diskon: number
  pph: number
  database_id: string
  updated_at: string
}

type PaymentRow = {
  po_id: number
  nomor_po: string
  nama_customer: string
  nomor_invoice: string
  grand_total: number
  total_paid: number
  outstanding: number
  status: 'LUNAS' | 'BELUM LUNAS'
  is_lunas: boolean
  updated_at: string
  latest_accurate_at: string
  database_id: string
  history: PaymentHistory[]
}

type PageProps = {
  rows: PaymentRow[]
  pagination: {
    page: number
    per_page: number
    total_rows: number
    total_pages: number
  }
  summary: {
    total: number
    shown: number
    lunas_on_page: number
    belum_lunas_on_page: number
  }
  filters: {
    q: string
    per_page: number
    page: number
  }
  refresh_seconds?: number
}

const ROUTE = '/monitoring/pembayaran-accurate'

const formatRupiah = (value: number) =>
  new Intl.NumberFormat('id-ID', {
    style: 'currency',
    currency: 'IDR',
    maximumFractionDigits: 0,
  }).format(value || 0)

export default function PaymentMonitor() {
  const { rows, pagination, summary, filters, refresh_seconds } = usePage<PageProps>().props
  const { t } = useAppText()
  const [isTableLoading, setIsTableLoading] = useState(false)
  const [isActionLoading, setIsActionLoading] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  const [form, setForm] = useState({
    q: filters.q || '',
    per_page: String(filters.per_page || 20),
  })

  useEffect(() => {
    setForm({
      q: filters.q || '',
      per_page: String(filters.per_page || 20),
    })
  }, [filters.q, filters.per_page])

  const appliedQuery = useMemo(
    () => ({
      q: filters.q || '',
      per_page: String(filters.per_page || 20),
      page: String(filters.page || 1),
    }),
    [filters.page, filters.per_page, filters.q]
  )

  const applyFilter = () => {
    router.get(
      ROUTE,
      {
        q: form.q.trim(),
        per_page: form.per_page,
        page: '1',
      },
      {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        only: ['rows', 'pagination', 'summary', 'filters'],
        onStart: () => setIsTableLoading(true),
        onFinish: () => setIsTableLoading(false),
      }
    )
  }

  const resetFilter = () => {
    setForm({ q: '', per_page: '20' })
    router.get(
      ROUTE,
      {},
      {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        only: ['rows', 'pagination', 'summary', 'filters'],
        onStart: () => setIsTableLoading(true),
        onFinish: () => setIsTableLoading(false),
      }
    )
  }

  const refreshNow = () => {
    router.get(
      ROUTE,
      appliedQuery,
      {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        only: ['rows', 'pagination', 'summary', 'filters'],
        onStart: () => setIsTableLoading(true),
        onFinish: () => setIsTableLoading(false),
      }
    )
  }

  useEffect(() => {
    const refreshMs = Math.max(3, Number(refresh_seconds || 10)) * 1000
    const interval = window.setInterval(() => {
      const active = document.activeElement as HTMLElement | null

      if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) {
        return
      }

      router.get(
        ROUTE,
        appliedQuery,
        {
          preserveState: true,
          preserveScroll: true,
          replace: true,
          only: ['rows', 'pagination', 'summary', 'filters'],
        }
      )
    }, refreshMs)

    return () => {
      window.clearInterval(interval)
    }
  }, [appliedQuery, refresh_seconds])

  const postAction = async (url: string, payload: Record<string, unknown>) => {
    const csrf =
      document
        .querySelector('meta[name="csrf-token"]')
        ?.getAttribute('content') ?? ''

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        'X-CSRF-TOKEN': csrf,
        'X-Requested-With': 'XMLHttpRequest',
      },
      body: JSON.stringify(payload),
    })

    const data = await response.json().catch(() => ({}))

    return { ok: response.ok && Boolean(data?.ok), data }
  }

  const handleResend = async (keyType: 'invoice' | 'receipt', keyNumber: string, databaseId?: string) => {
    if (!keyNumber || keyNumber === '-') {
      setMessage({ type: 'error', text: t('accurate_payment_monitoring.error_empty_transaction') })

      return
    }

    setIsActionLoading(true)

    try {
      const result = await postAction('/monitoring/pembayaran-accurate/resend-sales-receipt', {
        key_type: keyType,
        key_number: keyNumber,
        database_id: databaseId ?? '',
      })

      setMessage({
        type: result.ok ? 'success' : 'error',
        text: typeof result.data?.message === 'string'
          ? result.data.message
          : t('accurate_payment_monitoring.error_resend_failed'),
      })

      router.reload({
        preserveUrl: true,
        only: ['rows', 'pagination', 'summary', 'filters'],
      })
    } catch {
      setMessage({ type: 'error', text: t('accurate_payment_monitoring.error_resend_failed') })
    } finally {
      setIsActionLoading(false)
    }
  }

  const handleDeletePayment = async (paymentId: number) => {
    if (!window.confirm(t('accurate_payment_monitoring.confirm_delete_payment'))) {
return
}

    setIsActionLoading(true)

    try {
      const result = await postAction('/monitoring/pembayaran-accurate/delete-payment', {
        payment_id: paymentId,
      })

      setMessage({
        type: result.ok ? 'success' : 'error',
        text: typeof result.data?.message === 'string'
          ? result.data.message
          : t('accurate_payment_monitoring.error_delete_failed'),
      })

      if (result.ok) {
        router.reload({
          preserveUrl: true,
          only: ['rows', 'pagination', 'summary', 'filters'],
        })
      }
    } catch {
      setMessage({ type: 'error', text: t('accurate_payment_monitoring.error_delete_request_failed') })
    } finally {
      setIsActionLoading(false)
    }
  }

  const goToPage = (nextPage: number) => {
    if (nextPage < 1 || nextPage > pagination.total_pages) {
return
}

    router.get(
      ROUTE,
      {
        q: filters.q || '',
        per_page: String(filters.per_page || 20),
        page: String(nextPage),
      },
      {
        preserveState: true,
        preserveScroll: true,
        replace: true,
        only: ['rows', 'pagination', 'summary', 'filters'],
        onStart: () => setIsTableLoading(true),
        onFinish: () => setIsTableLoading(false),
      }
    )
  }

  return (
    <FinanceAppLayout>
      <Head title={t('accurate_payment_monitoring.page_title')} />

      <Main>
        <div className='mb-4 flex items-center justify-between'>
          <div>
            <h1 className='text-2xl font-bold tracking-tight text-foreground'>{t('accurate_payment_monitoring.title')}</h1>
            <p className='text-sm text-muted-foreground'>
            {t('accurate_payment_monitoring.subtitle')}
            </p>
            <p className='text-xs text-muted-foreground'>
              {t('accurate_payment_monitoring.auto_refresh', { seconds: Math.max(3, Number(refresh_seconds || 10)) })}
            </p>
          </div>
        </div>

        {message && (
          <div
            className={`mb-4 rounded-md border px-3 py-2 text-sm ${
              message.type === 'success'
                ? 'border-emerald-200 bg-emerald-50 text-emerald-700'
                : 'border-red-200 bg-red-50 text-red-700'
            }`}
          >
            {message.text}
          </div>
        )}

        <div className='mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4'>
          {[
            { label: t('accurate_payment_monitoring.card_total'), value: summary.total.toLocaleString('id-ID'), cls: '' },
            { label: t('accurate_payment_monitoring.card_shown'), value: summary.shown.toLocaleString('id-ID'), cls: '' },
            { label: t('accurate_payment_monitoring.card_paid'), value: summary.lunas_on_page.toLocaleString('id-ID'), cls: 'text-emerald-600' },
            { label: t('accurate_payment_monitoring.card_unpaid'), value: summary.belum_lunas_on_page.toLocaleString('id-ID'), cls: 'text-amber-600' },
          ].map((card) => (
            <Card key={card.label} className='gap-1 py-3 shadow-none'>
              <CardHeader className='px-4 pb-0 pt-2.5'>
                <CardTitle className='text-xs font-medium text-muted-foreground'>{card.label}</CardTitle>
              </CardHeader>
              <CardContent className='px-4 pb-2 pt-0'>
                <p className={`text-[2rem] leading-none font-bold ${card.cls}`}>{card.value}</p>
              </CardContent>
            </Card>
          ))}
        </div>

        <Card className='mb-4 gap-2 py-3 shadow-none'>
          <CardHeader className='px-4 gap-0'>
            <CardTitle className='text-sm font-semibold text-foreground'>{t('accurate_payment_monitoring.filter_title')}</CardTitle>
          </CardHeader>
          <CardContent className='px-4 pb-3 pt-0'>
            <div className='grid gap-2 md:grid-cols-[minmax(220px,1fr)_120px_auto]'>
              <Input
                value={form.q}
                onChange={(e) => setForm((prev) => ({ ...prev, q: e.target.value }))}
                placeholder={t('accurate_payment_monitoring.placeholder_search')}
                className='h-9'
              />
              <Input
                type='number'
                min={5}
                max={100}
                value={form.per_page}
                onChange={(e) => setForm((prev) => ({ ...prev, per_page: e.target.value }))}
                className='h-9'
              />
              <div className='flex flex-wrap gap-2'>
                <Button className='h-9' onClick={applyFilter}>{t('accurate_payment_monitoring.btn_apply')}</Button>
                <Button className='h-9' variant='outline' onClick={resetFilter}>{t('accurate_payment_monitoring.btn_reset')}</Button>
                <Button className='h-9' variant='secondary' onClick={refreshNow}>{t('accurate_payment_monitoring.btn_refresh')}</Button>
              </div>
            </div>
            <p className='mt-2 text-xs text-muted-foreground'>
              Total data: {pagination.total_rows.toLocaleString('id-ID')} | Halaman {pagination.page} dari {pagination.total_pages}
            </p>
          </CardContent>
        </Card>

            <div className='overflow-x-auto rounded-md border text-foreground'>
              <table className='w-full min-w-[1200px] border-collapse text-sm text-foreground'>
                <thead className='bg-muted/40'>
                  <tr className='border-b text-left text-xs font-medium text-muted-foreground'>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_no')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_po_number')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_customer')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_invoice')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_grand_total')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_payment_history')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_total_paid')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_outstanding')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_status')}</th>
                    <th className='px-2 py-1.5'>{t('accurate_payment_monitoring.col_accurate_updated')}</th>
                  </tr>
                </thead>
                <tbody className='text-foreground'>
                  {rows.length === 0 ? (
                    <tr>
                      <td colSpan={10} className='px-2 py-6 text-center text-sm text-muted-foreground'>
                        {t('accurate_payment_monitoring.empty_message')}
                      </td>
                    </tr>
                  ) : (
                    rows.map((row, index) => (
                      <tr key={row.po_id} className='border-b align-top text-foreground hover:bg-muted/20'>
                        <td className='px-2 py-1.5 text-xs'>
                          {(pagination.page - 1) * pagination.per_page + index + 1}
                        </td>
                        <td className='px-2 py-1.5 text-xs font-medium'>{row.nomor_po}</td>
                        <td className='px-2 py-1.5 text-xs'>{row.nama_customer}</td>
                        <td className='px-2 py-1.5 text-xs'>
                          <div>{row.nomor_invoice}</div>
                          <Button
                            type='button'
                            size='sm'
                            variant='outline'
                            className='mt-1 h-6 border-blue-200 bg-blue-50 px-2 text-[11px] text-blue-700 hover:bg-blue-100'
                            disabled={isActionLoading || row.nomor_invoice === '-'}
                            onClick={() => handleResend('invoice', row.nomor_invoice, row.database_id)}
                          >
                            {t('accurate_payment_monitoring.btn_resend_invoice')}
                          </Button>
                        </td>
                        <td className='px-2 py-1.5 text-xs'>{formatRupiah(row.grand_total)}</td>
                        <td className='px-2 py-1.5'>
                          {row.history.length === 0 ? (
                            <span className='text-[11px] text-muted-foreground'>{t('accurate_payment_monitoring.no_payment_history')}</span>
                          ) : (
                            <ul className='space-y-1.5'>
                              {row.history.map((history) => (
                                <li key={history.payment_id} className='rounded border bg-muted/20 p-1.5 text-[11px]'>
                                  <div>
                                    {history.nomor_bukti_bayar} | {formatRupiah(history.jumlah)}
                                    {history.diskon !== 0 ? ` (Diskon: ${formatRupiah(history.diskon)})` : ''}
                                    {history.pph !== 0 ? ` (PPH: ${formatRupiah(history.pph)})` : ''}
                                  </div>
                                  <div className='mt-0.5 text-muted-foreground'>{history.updated_at}</div>
                                  <div className='mt-1 flex flex-wrap gap-1.5'>
                                    <Button
                                      type='button'
                                      size='sm'
                                      variant='outline'
                                      className='h-6 border-blue-200 bg-blue-50 px-2 text-[11px] text-blue-700 hover:bg-blue-100'
                                      disabled={isActionLoading}
                                      onClick={() => handleResend('receipt', history.nomor_bukti_bayar, history.database_id)}
                                    >
                                      {t('accurate_payment_monitoring.btn_resend_receipt')}
                                    </Button>
                                    <Button
                                      type='button'
                                      size='sm'
                                      variant='destructive'
                                      className='h-6 px-2 text-[11px]'
                                      disabled={isActionLoading}
                                      onClick={() => handleDeletePayment(history.payment_id)}
                                    >
                                      {t('accurate_payment_monitoring.btn_delete_payment')}
                                    </Button>
                                  </div>
                                </li>
                              ))}
                            </ul>
                          )}
                        </td>
                        <td className='px-2 py-1.5 text-xs'>{formatRupiah(row.total_paid)}</td>
                        <td className='px-2 py-1.5 text-xs'>{formatRupiah(row.outstanding)}</td>
                        <td className='px-2 py-1.5'>
                          {row.status === 'LUNAS' ? (
                            <Badge className='h-5 bg-emerald-600 px-2 text-[11px] text-white'>{t('accurate_payment_monitoring.status_paid')}</Badge>
                          ) : (
                            <Badge variant='secondary' className='h-5 px-2 text-[11px]'>{t('accurate_payment_monitoring.status_unpaid')}</Badge>
                          )}
                        </td>
                        <td className='px-2 py-1.5 text-[11px]'>{row.latest_accurate_at || '-'}</td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>

            <div className='mt-3 flex items-center justify-between gap-2'>
              <Button
                variant='outline'
                disabled={pagination.page <= 1 || isTableLoading}
                onClick={() => goToPage(pagination.page - 1)}
              >
                {t('accurate_payment_monitoring.btn_prev')}
              </Button>
              <span className='text-sm text-muted-foreground'>
                {t('accurate_payment_monitoring.pagination_current', { page: pagination.page, total: pagination.total_pages })}
              </span>
              <Button
                variant='outline'
                disabled={pagination.page >= pagination.total_pages || isTableLoading}
                onClick={() => goToPage(pagination.page + 1)}
              >
                {t('accurate_payment_monitoring.btn_next')}
              </Button>
            </div>

        {(isTableLoading || isActionLoading) && (
          <div className='fixed inset-0 z-50 flex items-center justify-center bg-background/40 backdrop-blur-[1px]'>
            <div className='flex items-center gap-2 rounded-md border bg-background px-4 py-2 text-sm text-muted-foreground shadow-sm'>
              <Spinner className='size-4' />
              {t('accurate_payment_monitoring.loading_message')}
            </div>
          </div>
        )}
      </Main>
    </FinanceAppLayout>
  )
}
