import { useIsMobile } from '@/hooks/use-mobile';
import { authClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import type { ComplexWithRole } from '@repo/api-contract';
import { useState } from 'react';
import { BookingProvider, useBooking } from './booking-provider';
import { BookingCreateDialog } from './components/booking-create-dialog';
import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary';
import { BookingHeader } from './components/booking-header';
import { BookingListView } from './components/booking-list-view';
import { BookingMobile } from './components/booking-mobile';
import { BookingTimeline } from './components/booking-timeline';
import { BookingToolbar } from './components/booking-toolbar';
import { BookingToolsDialog } from './components/booking-tools-dialog';
import { RecurringBookingListView } from './components/recurring-booking-list';

interface BookingProps {
  complex: ComplexWithRole;
}

export function Booking({ complex }: BookingProps) {
  const { user } = useAuth();
  const [sending, setSending] = useState(false);
  const [emailSent, setEmailSent] = useState(false);

  const emailNotVerified = user && !user.emailVerified;

  const handleResendVerification = async () => {
    if (!user?.email || sending) return;
    setSending(true);
    try {
      await authClient.sendVerificationEmail({ email: user.email });
      setEmailSent(true);
      setTimeout(() => setEmailSent(false), 6000);
    } catch {
      // Silently fail — the banner already shows the email to contact
    } finally {
      setSending(false);
    }
  };

  return (
    <BookingProvider complex={complex}>
      {emailNotVerified && (
        <div className="mb-6 flex items-center justify-between gap-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:border-amber-800/30 dark:bg-amber-950/30 dark:text-amber-200">
          <span>
            No verificaste tu email. Para crear reservas necesitás verificar tu dirección de correo
            electrónico.
          </span>
          <button
            type="button"
            onClick={handleResendVerification}
            disabled={sending}
            className="shrink-0 rounded-lg bg-amber-200 px-3 py-1.5 text-xs font-medium text-amber-900 transition-colors hover:bg-amber-300 disabled:opacity-50 dark:bg-amber-800 dark:text-amber-50 dark:hover:bg-amber-700"
          >
            {sending ? 'Enviando...' : emailSent ? '¡Email enviado!' : 'Reenviar email'}
          </button>
        </div>
      )}
      <BookingInner />
      <BookingCreateDialog />
      <BookingToolsDialog />
    </BookingProvider>
  );
}

function BookingInner() {
  const { viewMode } = useBooking();
  const isMobile = useIsMobile();

  if (viewMode === 'list') {
    return <BookingListView />;
  }

  if (viewMode === 'recurring') {
    return <RecurringBookingListView />;
  }

  if (isMobile) {
    return <BookingMobile />;
  }

  return (
    <div className="flex flex-col gap-5">
      <BookingHeader />
      <BookingToolbar />
      <BookingTimeline />
      <div className="grid gap-5 xl:grid-cols-4">
        <BookingDaySummary />
        <BookingQuickActions />
      </div>
    </div>
  );
}
