import React, { ReactElement, useEffect } from 'react'
import Head from 'next/head'
import dayjs from 'dayjs'
import { mdiRoomServiceOutline } 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/service_requests/service_requestsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'

const DetailStat = ({ label, value, hint }: any) => (
  <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 }: any) => (
  <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 ? items.slice(0, 4).map((item) => <div key={item.id} className='mb-2 rounded-xl border border-white/10 bg-slate-950/40 px-3 py-2 text-sm text-slate-200'>{getLabel(item)}</div>) : <p className='text-sm text-slate-400'>{emptyLabel}</p>}
  </div>
)

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 service request currency', error)
    return `${amount} ${currency || ''}`.trim()
  }
}

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

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

  const roleLane = getRoleLaneFromUser(currentUser)
  const isCustomer = roleLane === 'customer'
  const canManagePlatformFields = roleLane === 'super_admin'
  const canManageOperationalFields = roleLane === 'super_admin' || roleLane === 'admin' || roleLane === 'concierge'
  const canManageCostFields = roleLane === 'super_admin' || roleLane === 'admin'
  const canEdit = currentUser && hasPermission(currentUser, 'UPDATE_SERVICE_REQUESTS')
  const pageTitle = isCustomer ? 'Support Request' : 'Service Request'

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

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

        <div className='mb-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4'>
          <DetailStat label='Request Type' value={service_requests?.request_type || 'custom_service'} hint='Service lane' />
          <DetailStat label='Status' value={service_requests?.status || 'new'} hint='Current workflow stage' />
          <DetailStat label='Priority' value={service_requests?.priority || 'normal'} hint='Delivery urgency' />
          <DetailStat label='Due At' value={formatDateTime(service_requests?.due_at)} hint={service_requests?.reservation?.reservation_code || 'Stay link 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'>Service snapshot</h2>
                  <p className='mt-1 text-sm text-slate-400'>What was requested, who owns it, and when it should be completed.</p>
                </div>

                <div className='grid gap-3 md:grid-cols-2'>
                  {canManagePlatformFields && <DetailRow label='Tenant' value={service_requests?.tenant?.name} />}
                  <DetailRow label='Stay' value={service_requests?.reservation?.reservation_code} />
                  {canManageOperationalFields && <DetailRow label='Requested by' value={service_requests?.requested_by?.firstName || service_requests?.requested_by?.email} />}
                  {canManageOperationalFields && <DetailRow label='Assigned to' value={service_requests?.assigned_to?.firstName || service_requests?.assigned_to?.email} />}
                  <DetailRow label='Requested at' value={formatDateTime(service_requests?.requested_at)} />
                  <DetailRow label='Completed at' value={formatDateTime(service_requests?.completed_at)} />
                </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'>Details</p>
                  <h2 className='mt-2 text-xl font-semibold text-white'>{service_requests?.summary || 'Support request details'}</h2>
                </div>

                <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'>Request context</p>
                  <p className='mt-2 text-sm leading-6 text-slate-100'>{service_requests?.details || 'No additional details shared yet.'}</p>
                </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'>Execution context</h2>
                <p className='mt-1 text-sm text-slate-400'>Files and related discussion attached to this request.</p>
              </div>

              <DetailRow label='Estimated Cost' value={canManageCostFields ? formatCurrency(service_requests?.estimated_cost, service_requests?.currency) : 'Restricted'} />
              <DetailRow label='Actual Cost' value={canManageCostFields ? formatCurrency(service_requests?.actual_cost, service_requests?.currency) : 'Restricted'} />
              <DetailRow label='Currency' value={service_requests?.currency} />

              <div className='space-y-3'>
                <RelatedList title='Documents' items={Array.isArray(service_requests?.documents) ? service_requests.documents : []} getLabel={(item) => item?.file_name || item?.document_type || item?.id} />
                <RelatedList title='Comments' items={Array.isArray(service_requests?.comments) ? service_requests.comments : []} getLabel={(item) => item?.comment_text || item?.body || item?.id} emptyLabel='No comments attached yet.' />
              </div>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    </>
  )
}

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

export default ServiceRequestsView
