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 { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { fetch } from '../../stores/reservations/reservationsSlice';
import LayoutAuthenticated from '../../layouts/Authenticated';
import { getPageTitle } from '../../config';
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton';
import SectionMain from '../../components/SectionMain';
import CardBox from '../../components/CardBox';
import BaseButton from '../../components/BaseButton';
import BaseButtons from '../../components/BaseButtons';
import { hasPermission } from '../../helpers/userPermissions';

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

type RelatedListProps = {
  title: string;
  items: any[];
  getLabel: (item: any) => string;
  emptyLabel?: 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' }: RelatedListProps) => (
  <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: any) => (
          <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>
        ))}
        {items.length > 4 && (
          <p className="text-xs uppercase tracking-[0.18em] text-slate-400">+{items.length - 4} more</p>
        )}
      </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 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 rate', 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 canEdit = currentUser && hasPermission(currentUser, 'UPDATE_RESERVATIONS');
  const plannedStay = `${formatDate(reservations?.check_in_at)} → ${formatDate(reservations?.check_out_at)}`;
  const actualStay =
    reservations?.actual_check_in_at || reservations?.actual_check_out_at
      ? `${formatDate(reservations?.actual_check_in_at)} → ${formatDate(reservations?.actual_check_out_at)}`
      : 'Not checked in yet';

  return (
    <>
      <Head>
        <title>{getPageTitle('Reservation')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCalendarCheck} title="Reservation" 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 reservation state" />
          <DetailStat label="Planned Stay" value={plannedStay} hint="Scheduled check-in and check-out" />
          <DetailStat
            label="Guest Count"
            value={reservations?.guest_count || 0}
            hint={formatCurrency(reservations?.nightly_rate, reservations?.currency)}
          />
        </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 summary</h2>
                  <p className="mt-1 text-sm text-slate-400">
                    The essential operating details for the stay, inventory assignment, and guest timing.
                  </p>
                </div>

                <div className="grid gap-3 md:grid-cols-2">
                  <DetailRow label="Property" value={reservations?.property?.name} />
                  <DetailRow label="Unit" value={reservations?.unit?.name || reservations?.unit?.unit_number} />
                  <DetailRow label="Unit Type" value={reservations?.unit_type?.name} />
                  <DetailRow label="Booking Request" value={reservations?.booking_request?.request_code} />
                  <DetailRow label="Tenant" value={reservations?.tenant?.name} />
                  {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
                    <DetailRow label="Organization" value={reservations?.organization?.name} />
                  )}
                  <DetailRow label="Early Check-in" value={reservations?.early_check_in ? 'Yes' : 'No'} />
                  <DetailRow label="Late Check-out" value={reservations?.late_check_out ? 'Yes' : 'No'} />
                  <DetailRow label="Monthly Rate" value={formatCurrency(reservations?.monthly_rate, reservations?.currency)} />
                  <DetailRow label="Actual Stay" value={actualStay} />
                </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">Internal and guest-facing notes</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">Internal Notes</p>
                    <p className="mt-2 text-sm leading-6 text-slate-100">
                      {reservations?.internal_notes || 'No internal notes recorded.'}
                    </p>
                  </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">External Notes</p>
                    <p className="mt-2 text-sm leading-6 text-slate-100">
                      {reservations?.external_notes || 'No guest-facing notes recorded.'}
                    </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">Activity</p>
                <h2 className="mt-2 text-xl font-semibold text-white">Connected operations</h2>
                <p className="mt-1 text-sm text-slate-400">A simple view of guest, service, billing, and document activity.</p>
              </div>

              <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?.request_title || item?.status || item?.id}
                />
                <RelatedList
                  title="Invoices"
                  items={Array.isArray(reservations?.invoices) ? reservations.invoices : []}
                  getLabel={(item) => item?.invoice_number || item?.status || item?.id}
                />
                <RelatedList
                  title="Documents"
                  items={Array.isArray(reservations?.documents) ? reservations.documents : []}
                  getLabel={(item) => item?.name || item?.document_name || item?.id}
                />
              </div>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    </>
  );
};

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

export default ReservationsView;
