import React, { ReactElement, useEffect } from 'react';
import Head from 'next/head';
import dayjs from 'dayjs';
import { mdiClipboardTextOutline } from '@mdi/js';
import { useRouter } from 'next/router';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { fetch } from '../../stores/booking_requests/booking_requestsSlice';
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 booking request budget', error);
    return `${amount} ${currency || ''}`.trim();
  }
};

const BookingRequestsView = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { booking_requests } = useAppSelector((state) => state.booking_requests);
  const { currentUser } = useAppSelector((state) => state.auth);
  const { id } = router.query;

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

  const canEdit = currentUser && hasPermission(currentUser, 'UPDATE_BOOKING_REQUESTS');
  const canManageInternalFields = Boolean(currentUser?.app_role?.globalAccess);
  const pageTitle = canManageInternalFields ? 'Booking Request' : 'Stay Request';
  const overviewHeading = canManageInternalFields ? 'Guest request snapshot' : 'Stay request snapshot';
  const overviewCopy = canManageInternalFields
    ? 'A light summary of who requested the stay, where they prefer to stay, and what needs follow-up.'
    : 'A light summary of the requested stay, preferred accommodation, and what still needs follow-up.';
  const stayWindow =
    booking_requests?.check_in_at || booking_requests?.check_out_at
      ? `${formatDate(booking_requests?.check_in_at)} → ${formatDate(booking_requests?.check_out_at)}`
      : 'Dates not set';

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

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

        <div className="mb-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
          <DetailStat label="Request Code" value={booking_requests?.request_code || 'Draft'} hint="Booking workflow reference" />
          <DetailStat label="Status" value={booking_requests?.status || 'Draft'} hint="Current approval stage" />
          <DetailStat label="Stay Window" value={stayWindow} hint="Requested check-in and check-out" />
          <DetailStat
            label="Budget"
            value={formatCurrency(booking_requests?.max_budget_amount, booking_requests?.currency)}
            hint={`${booking_requests?.guest_count || 0} guest${Number(booking_requests?.guest_count || 0) === 1 ? '' : 's'}`}
          />
        </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">{overviewHeading}</h2>
                  <p className="mt-1 text-sm text-slate-400">{overviewCopy}</p>
                </div>

                <div className="grid gap-3 md:grid-cols-2">
                  {canManageInternalFields && (
                    <>
                      <DetailRow
                        label="Requested By"
                        value={booking_requests?.requested_by?.firstName || booking_requests?.requested_by?.email}
                      />
                      <DetailRow label="Tenant" value={booking_requests?.tenant?.name} />
                      {hasPermission(currentUser, 'READ_ORGANIZATIONS') && (
                        <DetailRow label="Organization" value={booking_requests?.organization?.name} />
                      )}
                    </>
                  )}
                  <DetailRow label="Preferred Property" value={booking_requests?.preferred_property?.name} />
                  <DetailRow label="Preferred Unit Type" value={booking_requests?.preferred_unit_type?.name} />
                  <DetailRow label="Preferred Bedrooms" value={booking_requests?.preferred_bedrooms} />
                  <DetailRow label="Budget Code" value={booking_requests?.budget_code} />
                  <DetailRow label="Currency" value={booking_requests?.currency} />
                </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 context</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">Purpose of Stay</p>
                    <p className="mt-2 text-sm leading-6 text-slate-100">
                      {booking_requests?.purpose_of_stay || 'No additional purpose provided.'}
                    </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">Special Requirements</p>
                    <p className="mt-2 text-sm leading-6 text-slate-100">
                      {booking_requests?.special_requirements || 'No special requirements 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">Linked records</h2>
                <p className="mt-1 text-sm text-slate-400">The most relevant downstream items tied to this request.</p>
              </div>

              <div className="space-y-3">
                <RelatedList
                  title="Travelers"
                  items={Array.isArray(booking_requests?.travelers) ? booking_requests.travelers : []}
                  getLabel={(item) => item?.full_name || item?.email || item?.id}
                />
                <RelatedList
                  title="Approval Steps"
                  items={Array.isArray(booking_requests?.approval_steps) ? booking_requests.approval_steps : []}
                  getLabel={(item) => item?.step_name || item?.status || item?.id}
                />
                <RelatedList
                  title="Documents"
                  items={Array.isArray(booking_requests?.documents) ? booking_requests.documents : []}
                  getLabel={(item) => item?.name || item?.document_name || item?.id}
                />
                <RelatedList
                  title="Reservations"
                  items={
                    Array.isArray(booking_requests?.reservations_booking_request)
                      ? booking_requests.reservations_booking_request
                      : []
                  }
                  getLabel={(item) => item?.reservation_code || item?.status || item?.id}
                  emptyLabel="No reservations have been created from this request."
                />
              </div>
            </div>
          </CardBox>
        </div>
      </SectionMain>
    </>
  );
};

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

export default BookingRequestsView;
