import React, { ReactElement, useEffect } from 'react'
import Head from 'next/head'
import dayjs from 'dayjs'
import { mdiCalendarCheck } from '@mdi/js'
import { useRouter } from 'next/router'

import BaseButton from '../../components/BaseButton'
import BaseButtons from '../../components/BaseButtons'
import CardBox from '../../components/CardBox'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'
import { getRoleLaneFromUser } from '../../helpers/roleLanes'
import { hasPermission } from '../../helpers/userPermissions'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { fetch } from '../../stores/reservations/reservationsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'

type StatProps = {
  label: string
  value: string | number
  hint?: string
}

const DetailStat = ({ label, value, hint }: StatProps) => (
  <CardBox className='rounded-2xl border border-white/10 shadow-none'>
    <div className='space-y-2'>
      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>{label}</p>
      <p className='text-2xl font-semibold text-white'>{value}</p>
      {hint && <p className='text-sm text-slate-400'>{hint}</p>}
    </div>
  </CardBox>
)

const DetailRow = ({ label, value }: { label: string; value?: React.ReactNode }) => (
  <div className='rounded-2xl border border-white/10 bg-white/5 px-4 py-3'>
    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>{label}</p>
    <div className='mt-2 text-sm leading-6 text-slate-100'>{value || 'Not set'}</div>
  </div>
)

const RelatedList = ({ title, items, getLabel, emptyLabel = 'No items yet' }: any) => (
  <div className='rounded-2xl border border-white/10 bg-white/5 px-4 py-4'>
    <div className='mb-3 flex items-center justify-between gap-3'>
      <p className='text-sm font-semibold text-white'>{title}</p>
      <span className='rounded-full border border-white/10 px-2.5 py-1 text-xs text-slate-300'>{items.length}</span>
    </div>

    {items.length ? (
      <div className='space-y-2'>
        {items.slice(0, 4).map((item) => (
          <div key={item.id} className='rounded-xl border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-200'>
            {getLabel(item)}
          </div>
        ))}
      </div>
    ) : (
      <p className='text-sm text-slate-400'>{emptyLabel}</p>
    )}
  </div>
)

const formatDate = (value?: string) => (value ? dayjs(value).format('MMM D, YYYY') : 'Not set')
const formatDateTime = (value?: string) => (value ? dayjs(value).format('MMM D, YYYY h:mm A') : 'Not set')
const formatCurrency = (amount?: string | number, currency?: string) => {
  if (amount === undefined || amount === null || amount === '') return 'Not set'

  try {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currency || 'USD',
      maximumFractionDigits: 0,
    }).format(Number(amount))
  } catch (error) {
    console.error('Failed to format reservation currency', error)
    return `${amount} ${currency || ''}`.trim()
  }
}

const ReservationsView = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const { reservations } = useAppSelector((state) => state.reservations)
  const { currentUser } = useAppSelector((state) => state.auth)
  const { id } = router.query

  useEffect(() => {
    dispatch(fetch({ id }))
  }, [dispatch, id])

  const roleLane = getRoleLaneFromUser(currentUser)
  const canManagePlatformFields = roleLane === 'super_admin'
  const canManageFinancialFields = canManagePlatformFields || roleLane === 'admin'
  const canEdit = currentUser && hasPermission(currentUser, 'UPDATE_RESERVATIONS')
  const pageTitle = roleLane === 'customer' ? 'My Stay' : 'Stay Details'
  const stayWindow = reservations?.check_in_at || reservations?.check_out_at
    ? `${formatDate(reservations?.check_in_at)} → ${formatDate(reservations?.check_out_at)}`
    : 'Dates not set'

  return (
    <>
      <Head>
        <title>{getPageTitle(pageTitle)}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCalendarCheck} title={pageTitle} main>
          <BaseButtons noWrap>
            <BaseButton href='/reservations/reservations-list' color='whiteDark' outline label='Back' />
            {canEdit && <BaseButton color='info' label='Edit' href={`/reservations/reservations-edit/?id=${id}`} />}
          </BaseButtons>
        </SectionTitleLineWithButton>

        <div className='mb-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4'>
          <DetailStat label='Reservation Code' value={reservations?.reservation_code || 'Pending'} hint='Stay reference' />
          <DetailStat label='Status' value={reservations?.status || 'quoted'} hint='Current stay stage' />
          <DetailStat label='Stay Window' value={stayWindow} hint='Scheduled dates' />
          <DetailStat label='Guests' value={reservations?.guest_count || 0} hint={reservations?.unit?.unit_number || 'Unit pending'} />
        </div>

        <div className='grid gap-6 xl:grid-cols-[minmax(0,1.4fr)_minmax(320px,0.9fr)]'>
          <div className='space-y-6'>
            <CardBox className='rounded-2xl border border-white/10 shadow-none'>
              <div className='space-y-4'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.2em] text-slate-400'>Overview</p>
                  <h2 className='mt-2 text-xl font-semibold text-white'>Stay snapshot</h2>
                  <p className='mt-1 text-sm text-slate-400'>Housing assignment, dates, and the most important execution details.</p>
                </div>

                <div className='grid gap-3 md:grid-cols-2'>
                  {canManagePlatformFields && (
                    <>
                      <DetailRow label='Tenant' value={reservations?.tenant?.name} />
                      <DetailRow label='Organization' value={reservations?.organization?.name} />
                    </>
                  )}
                  <DetailRow label='Source Request' value={reservations?.booking_request?.request_code} />
                  <DetailRow label='Property' value={reservations?.property?.name} />
                  <DetailRow label='Unit' value={reservations?.unit?.unit_number} />
                  <DetailRow label='Unit Type' value={reservations?.unit_type?.name} />
                  <DetailRow label='Actual Check-in' value={formatDateTime(reservations?.actual_check_in_at)} />
                  <DetailRow label='Actual Check-out' value={formatDateTime(reservations?.actual_check_out_at)} />
                  <DetailRow label='Early Check-in' value={reservations?.early_check_in ? 'Yes' : 'No'} />
                  <DetailRow label='Late Check-out' value={reservations?.late_check_out ? 'Yes' : 'No'} />
                </div>
              </div>
            </CardBox>

            <CardBox className='rounded-2xl border border-white/10 shadow-none'>
              <div className='space-y-4'>
                <div>
                  <p className='text-xs font-semibold uppercase tracking-[0.2em] text-slate-400'>Notes</p>
                  <h2 className='mt-2 text-xl font-semibold text-white'>Stay coordination</h2>
                </div>

                <div className='grid gap-3 md:grid-cols-2'>
                  <div className='rounded-2xl border border-white/10 bg-white/5 px-4 py-4'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>Guest-facing notes</p>
                    <p className='mt-2 text-sm leading-6 text-slate-100'>{reservations?.external_notes || 'No guest-facing notes yet.'}</p>
                  </div>
                  {canManageFinancialFields && (
                    <div className='rounded-2xl border border-white/10 bg-white/5 px-4 py-4'>
                      <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>Internal notes</p>
                      <p className='mt-2 text-sm leading-6 text-slate-100'>{reservations?.internal_notes || 'No internal notes yet.'}</p>
                    </div>
                  )}
                </div>
              </div>
            </CardBox>
          </div>

          <CardBox className='rounded-2xl border border-white/10 shadow-none'>
            <div className='space-y-4'>
              <div>
                <p className='text-xs font-semibold uppercase tracking-[0.2em] text-slate-400'>Linked records</p>
                <h2 className='mt-2 text-xl font-semibold text-white'>Operational context</h2>
                <p className='mt-1 text-sm text-slate-400'>Everything directly attached to this stay.</p>
              </div>

              <DetailRow label='Nightly Rate' value={canManageFinancialFields ? formatCurrency(reservations?.nightly_rate, reservations?.currency) : 'Restricted'} />
              <DetailRow label='Monthly Rate' value={canManageFinancialFields ? formatCurrency(reservations?.monthly_rate, reservations?.currency) : 'Restricted'} />
              <DetailRow label='Currency' value={reservations?.currency} />

              <div className='space-y-3'>
                <RelatedList title='Guests' items={Array.isArray(reservations?.guests) ? reservations.guests : []} getLabel={(item) => item?.full_name || item?.email || item?.id} />
                <RelatedList title='Service Requests' items={Array.isArray(reservations?.service_requests) ? reservations.service_requests : []} getLabel={(item) => item?.summary || item?.request_type || item?.id} />
                <RelatedList title='Documents' items={Array.isArray(reservations?.documents) ? reservations.documents : []} getLabel={(item) => item?.file_name || item?.document_type || item?.id} />
                <RelatedList title='Invoices' items={Array.isArray(reservations?.invoices) ? reservations.invoices : []} getLabel={(item) => item?.invoice_number || item?.status || item?.id} emptyLabel='No invoices linked yet.' />
              </div>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    </>
  )
}

ReservationsView.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_RESERVATIONS'}>{page}</LayoutAuthenticated>
}

export default ReservationsView
