import { Button } from '@/components/ui/button';
import {
  ResponsiveDialog,
  ResponsiveDialogClose,
  ResponsiveDialogContent,
  ResponsiveDialogDescription,
  ResponsiveDialogFooter,
  ResponsiveDialogHeader,
  ResponsiveDialogTitle,
} from '@/components/ui/responsive-dialog';
import { Separator } from '@/components/ui/separator';
import { useIsMobile } from '@/hooks/use-mobile';
import { cn } from '@/lib/utils';
import {
  AlertTriangle,
  BadgeCheck,
  CalendarDays,
  CheckCircle2,
  Clock,
  MapPin,
  MessageCircle,
  Phone,
  User,
  Wrench,
  XCircle,
} from 'lucide-react';
import { useState } from 'react';
import { useBooking } from '../booking-provider';

function formatDate(date: string | undefined) {
  if (!date) return '';

  const formatted = new Intl.DateTimeFormat('es-AR', {
    weekday: 'long',
    day: 'numeric',
    month: 'long',
  }).format(new Date(`${date}T00:00:00`));

  return formatted
    .split(' ')
    .map((word, index) => {
      if (index === 0 || index === 3) {
        return word.charAt(0).toUpperCase() + word.slice(1);
      }
      return word;
    })
    .join(' ');
}

const statusConfig: Record<string, { label: string; className: string }> = {
  CONFIRMED: {
    label: 'Reservada',
    className: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30',
  },
  COMPLETED: {
    label: 'Completada',
    className: 'bg-sky-500/15 text-sky-400 border-sky-500/30',
  },
  CANCELLED: {
    label: 'Cancelada',
    className: 'bg-red-500/15 text-red-400 border-red-500/30',
  },
  NOSHOW: {
    label: 'No show',
    className: 'bg-amber-500/15 text-amber-400 border-amber-500/30',
  },
};

export function BookingToolsDialog() {
  const { selectedSegment, bookingToolsOpen, closeBookingTools, updateBookingStatus } =
    useBooking();
  const isMobile = useIsMobile();
  const booking = selectedSegment?.booking;
  const [confirmCancelOpen, setConfirmCancelOpen] = useState(false);

  const status = statusConfig[booking?.status ?? 'CONFIRMED'] ?? {
    label: booking?.status,
    className: 'bg-slate-500/15 text-slate-300 border-slate-500/30',
  };

  const sendWhatsappReminder = () => {
    const phone = booking?.customerPhone;
    if (!phone) return;

    const message = `
        Hola ${booking?.customerName}. \nTe recordamos que tenés una reserva para el día *${formatDate(booking?.date)} de ${booking?.startTime} a ${booking?.endTime} en la cancha ${booking?.courtName} (${booking?.sport?.name})*. ¡Te esperamos! \nSi no vas a poder asistir, por favor avisanos para que otros clientes puedan reservar. Gracias.\n\n*Equipo de ${booking?.complexName}*`;

    const url = `https://wa.me/${phone}?text=${encodeURIComponent(message)}`;
    window.open(url, '_blank');
  };

  const updateStatus = (nextStatus: 'CANCELLED' | 'COMPLETED' | 'NOSHOW') => {
    if (!booking?.id) return;
    updateBookingStatus(booking.id, nextStatus);
    closeBookingTools();
  };

  const cancelConfirmDialog = (
    <ResponsiveDialog
      open={confirmCancelOpen}
      onOpenChange={(open) => !open && setConfirmCancelOpen(false)}
    >
      <ResponsiveDialogContent>
        <ResponsiveDialogHeader>
          <ResponsiveDialogTitle>¿Cancelar reserva?</ResponsiveDialogTitle>
          <ResponsiveDialogDescription>
            Esta acción no se puede deshacer. Se eliminará la reserva y la cancha volverá a estar
            disponible.
          </ResponsiveDialogDescription>
        </ResponsiveDialogHeader>

        <div className="space-y-2 rounded-lg border bg-card p-4">
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">Cliente</span>
            <span className="text-sm font-medium">{booking?.customerName ?? '-'}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">Cancha</span>
            <span className="text-sm font-medium">{booking?.courtName ?? '-'}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">Fecha</span>
            <span className="text-sm font-medium">{formatDate(booking?.date) || '-'}</span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">Horario</span>
            <span className="text-sm font-medium">
              {booking?.startTime ?? '--:--'} a {booking?.endTime ?? '--:--'}
            </span>
          </div>
        </div>

        <ResponsiveDialogFooter>
          <ResponsiveDialogClose asChild>
            <Button variant="outline">Volver</Button>
          </ResponsiveDialogClose>
          <Button
            variant="destructive"
            onClick={() => {
              setConfirmCancelOpen(false);
              updateStatus('CANCELLED');
            }}
          >
            Sí, cancelar reserva
          </Button>
        </ResponsiveDialogFooter>
      </ResponsiveDialogContent>
    </ResponsiveDialog>
  );

  if (isMobile) {
    return (
      <>
        <ResponsiveDialog
          open={bookingToolsOpen}
          onOpenChange={(open) => !open && closeBookingTools()}
        >
          <ResponsiveDialogContent
            className="data-[variant=drawer]:!h-[92dvh] data-[variant=drawer]:!max-h-[92dvh] data-[variant=drawer]:overflow-hidden data-[variant=drawer]:px-0 data-[variant=drawer]:pb-0"
            onOpenAutoFocus={(event) => event.preventDefault()}
          >
            <MobileBookingToolsSheet
              status={status}
              onComplete={() => updateStatus('COMPLETED')}
              onCancel={() => setConfirmCancelOpen(true)}
              onReminder={sendWhatsappReminder}
              onNoShow={() => updateStatus('NOSHOW')}
            />
          </ResponsiveDialogContent>
        </ResponsiveDialog>
        {cancelConfirmDialog}
      </>
    );
  }

  return (
    <>
      <ResponsiveDialog
        open={bookingToolsOpen}
        onOpenChange={(open) => !open && closeBookingTools()}
      >
        <ResponsiveDialogContent
          className="data-[variant=dialog]:max-w-5xl data-[variant=drawer]:max-h-[92dvh] data-[variant=drawer]:overflow-y-auto data-[variant=drawer]:px-4 data-[variant=drawer]:pb-5"
          onOpenAutoFocus={(event) => event.preventDefault()}
        >
          <ResponsiveDialogHeader className="data-[variant=drawer]:px-0 data-[variant=drawer]:text-left">
            <ResponsiveDialogTitle>Detalles de la reserva</ResponsiveDialogTitle>
            <ResponsiveDialogDescription>
              Administra la reserva y su estado.
            </ResponsiveDialogDescription>
          </ResponsiveDialogHeader>

          <section className="mx-0 px-0 pt-3 pb-3 sm:-mx-6 sm:px-6 sm:pb-5">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3 sm:gap-0">
              <DetailItem
                icon={<MapPin className="h-5 w-5" />}
                label="Cancha"
                value={selectedSegment?.booking?.courtName ?? '-'}
                helper={selectedSegment?.booking?.sport?.name}
                withDivider
              />

              <DetailItem
                icon={<BadgeCheck className="h-5 w-5" />}
                label="Estado actual"
                value={status.label}
                valueClassName="text-emerald-400 uppercase dark:text-emerald-500"
                withDivider
              />

              <DetailItem
                icon={<User className="h-5 w-5" />}
                label="Cliente"
                value={selectedSegment?.booking?.customerName ?? '-'}
              />

              <DetailItem
                icon={<Clock className="h-5 w-5" />}
                label="Fecha"
                value={`${formatDate(selectedSegment?.booking?.date)}`}
                withDivider
                className="sm:pt-10"
              />

              <DetailItem
                icon={<Clock className="h-5 w-5" />}
                label="Hora"
                value={`${selectedSegment?.booking?.startTime} a ${selectedSegment?.booking?.endTime}`}
                withDivider
                className="sm:pt-10"
              />

              <DetailItem
                icon={<Phone className="h-5 w-5" />}
                label="Teléfono"
                value={selectedSegment?.booking?.customerPhone ?? '-'}
                className="sm:pt-10"
              />
            </div>
          </section>

          <Separator className="dark:bg-slate-800 bg-slate-300" />

          {booking?.status !== 'COMPLETED' && (
            <section className="space-y-3">
              <div>
                <h3 className="font-medium text-slate-100">Acciones disponibles</h3>
                <p className="text-sm text-slate-400">
                  Elegí qué hacer según lo que ocurrió con el cliente.
                </p>
              </div>
              <div className="grid gap-3 sm:grid-cols-2">
                <ActionButton
                  icon={<CheckCircle2 className="h-5 w-5" />}
                  title="Completar reserva"
                  description="El cliente se presentó para usar la cancha."
                  className="border-emerald-500/40 bg-emerald-500/10 text-lg text-emerald-600 hover:bg-emerald-500/15 hover:text-emerald-800"
                  onClick={() => {
                    updateStatus('COMPLETED');
                  }}
                />

                <ActionButton
                  icon={<XCircle className="h-5 w-5" />}
                  title="Cancelar reserva"
                  description="El cliente avisó que no va a venir. La cancha vuelve a estar disponible."
                  className="border-red-500/40 bg-red-500/10 text-lg text-red-600 hover:bg-red-500/15 hover:text-red-800"
                  onClick={() => setConfirmCancelOpen(true)}
                />

                <ActionButton
                  icon={<MessageCircle className="h-5 w-5" />}
                  title="Enviar recordatorio"
                  description="Enviar un mensaje por WhatsApp al cliente."
                  className="border-sky-500/40 bg-sky-500/10 text-lg text-sky-600 hover:bg-sky-500/15 hover:text-sky-800"
                  onClick={sendWhatsappReminder}
                />

                <ActionButton
                  icon={<AlertTriangle className="h-5 w-5" />}
                  title="Marcar como No Show"
                  description="El cliente no vino y no canceló."
                  className="border-amber-500/40 bg-amber-500/10 text-lg text-amber-600 hover:bg-amber-500/15 hover:text-amber-800"
                  onClick={() => {
                    updateStatus('NOSHOW');
                  }}
                />
              </div>
            </section>
          )}

          <ResponsiveDialogFooter className="data-[variant=drawer]:px-0">
            <ResponsiveDialogClose asChild>
              <Button variant="outline" className="data-[variant=drawer]:h-11">
                Cerrar
              </Button>
            </ResponsiveDialogClose>
          </ResponsiveDialogFooter>
        </ResponsiveDialogContent>
      </ResponsiveDialog>
      {cancelConfirmDialog}
    </>
  );
}

function MobileBookingToolsSheet({
  status,
  onComplete,
  onCancel,
  onReminder,
  onNoShow,
}: {
  status: { label: string | undefined; className: string };
  onComplete: () => void;
  onCancel: () => void;
  onReminder: () => void;
  onNoShow: () => void;
}) {
  const { selectedSegment } = useBooking();
  const booking = selectedSegment?.booking;

  return (
    <div className="flex min-h-0 flex-1 flex-col pt-3">
      <ResponsiveDialogHeader className="shrink-0 px-4 pb-3 text-left">
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <ResponsiveDialogTitle className="text-lg">Reserva</ResponsiveDialogTitle>
            <ResponsiveDialogDescription>
              {booking?.courtName ?? '-'} · {booking?.startTime ?? '--:--'} a{' '}
              {booking?.endTime ?? '--:--'}
            </ResponsiveDialogDescription>
          </div>
          <span
            className={cn(
              'shrink-0 rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-normal',
              status.className
            )}
          >
            {status.label ?? '-'}
          </span>
        </div>
      </ResponsiveDialogHeader>

      <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">
        <section className="rounded-lg border border-border/70 bg-card/75 p-4">
          <div className="flex items-center gap-3">
            <div className="flex size-12 shrink-0 items-center justify-center rounded-lg bg-primary/15 text-primary">
              <MapPin className="size-6" />
            </div>
            <div className="min-w-0">
              <p className="text-xs text-muted-foreground">Cancha</p>
              <p className="truncate text-xl font-semibold">{booking?.courtName ?? '-'}</p>
              <p className="text-sm text-muted-foreground">{booking?.sport?.name ?? '-'}</p>
            </div>
          </div>
        </section>

        <section className="mt-3 grid gap-2">
          <MobileDetailRow
            icon={<User className="size-5" />}
            label="Cliente"
            value={booking?.customerName ?? '-'}
          />
          <MobileDetailRow
            icon={<Phone className="size-5" />}
            label="Teléfono"
            value={booking?.customerPhone ?? '-'}
          />
          <MobileDetailRow
            icon={<CalendarDays className="size-5" />}
            label="Fecha"
            value={formatDate(booking?.date) || '-'}
          />
          <MobileDetailRow
            icon={<Clock className="size-5" />}
            label="Horario"
            value={`${booking?.startTime ?? '--:--'} a ${booking?.endTime ?? '--:--'}`}
          />
          <MobileDetailRow
            icon={<Wrench className="size-5" />}
            label="Estado"
            value={status.label ?? '-'}
            valueClassName="uppercase text-primary"
          />
        </section>
      </div>

      {booking?.status !== 'COMPLETED' && (
        <section className="shrink-0 border-t border-border/70 bg-popover/95 px-4 py-3">
          <h3 className="text-sm font-medium">Acciones</h3>
          <div className="mt-3 grid grid-cols-2 gap-2">
            <MobileActionButton
              icon={<CheckCircle2 className="size-5" />}
              label="Completar"
              className="border-primary/45 bg-primary/12 text-primary"
              onClick={onComplete}
            />
            <MobileActionButton
              icon={<MessageCircle className="size-5" />}
              label="Recordar"
              className="border-reserved/45 bg-reserved/12 text-reserved"
              onClick={onReminder}
            />
            <MobileActionButton
              icon={<XCircle className="size-5" />}
              label="Cancelar"
              className="border-destructive/45 bg-destructive/12 text-destructive"
              onClick={onCancel}
            />
            <MobileActionButton
              icon={<AlertTriangle className="size-5" />}
              label="No show"
              className="border-warning/50 bg-warning/12 text-warning"
              onClick={onNoShow}
            />
          </div>
          <ResponsiveDialogFooter className="px-0 pb-0 pt-3">
            <ResponsiveDialogClose asChild>
              <Button variant="outline" className="h-11 w-full rounded-lg">
                Cerrar
              </Button>
            </ResponsiveDialogClose>
          </ResponsiveDialogFooter>
        </section>
      )}
    </div>
  );
}

function MobileDetailRow({
  icon,
  label,
  value,
  valueClassName,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  valueClassName?: string;
}) {
  return (
    <div className="flex items-center gap-3 rounded-lg border border-border/60 bg-secondary/35 p-3">
      <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-secondary text-muted-foreground">
        {icon}
      </div>
      <div className="min-w-0">
        <p className="text-xs text-muted-foreground">{label}</p>
        <p className={cn('truncate text-base font-semibold', valueClassName)}>{value}</p>
      </div>
    </div>
  );
}

function MobileActionButton({
  icon,
  label,
  className,
  onClick,
}: {
  icon: React.ReactNode;
  label: string;
  className: string;
  onClick: () => void;
}) {
  return (
    <Button
      type="button"
      variant="outline"
      className={cn('h-14 justify-start rounded-lg px-3 text-sm font-semibold', className)}
      onClick={onClick}
    >
      {icon}
      {label}
    </Button>
  );
}

function DetailItem({
  icon,
  label,
  value,
  helper,
  valueClassName,
  withDivider,
  className,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  helper?: string;
  valueClassName?: string;
  withDivider?: boolean;
  className?: string;
}) {
  return (
    <div
      className={cn(
        'relative flex items-start gap-4 rounded-lg bg-secondary/45 p-3 sm:bg-transparent sm:px-5 sm:py-1',
        className
      )}
    >
      {withDivider && (
        <div
          className="
                        absolute
                        right-0
                        top-1/2
                        hidden
                        h-16
                        w-px
                        -translate-y-1/2
                        dark:bg-slate-800
                        bg-slate-300
                        sm:block
                        "
        />
      )}

      <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg bg-slate-300/80 text-slate-800 dark:bg-slate-800/80 dark:text-slate-300">
        {icon}
      </div>
      <div className="min-w-0">
        <p className="text-sm text-slate-400">{label}</p>
        <p
          className={cn(
            'mt-1 text-lg leading-tight font-semibold tracking-normal text-gray-600 sm:text-[22px] dark:text-white',
            valueClassName
          )}
        >
          {value}
        </p>
        {helper && <p className="mt-1 text-sm text-slate-500">{helper}</p>}
      </div>
    </div>
  );
}

function ActionButton({
  icon,
  title,
  description,
  className,
  onClick,
}: {
  icon: React.ReactNode;
  title: string;
  description: string;
  className: string;
  onClick?: () => void;
}) {
  return (
    <Button
      type="button"
      variant="outline"
      className={`h-auto min-h-[76px] justify-start rounded-lg p-4 text-left ${className}`}
      onClick={onClick}
    >
      <div className="flex gap-3">
        <div className="mt-0.5">{icon}</div>
        <div>
          <p className="font-semibold">{title}</p>
          <p className="mt-1 whitespace-normal text-sm font-normal leading-relaxed dark:text-slate-200 text-slate-500">
            {description}
          </p>
        </div>
      </div>
    </Button>
  );
}
