import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import type { RecurringBookingGroup } from '@repo/api-contract';
import { ArrowLeft, Clock, MapPin, Pencil, Repeat, Trash2, User } from 'lucide-react';
import { useState } from 'react';
import { useBooking } from '../booking-provider';
import { RecurringBookingEditDialog } from './recurring-booking-edit-dialog';

const DAY_LABELS: Record<string, string> = {
  MONDAY: 'Lunes',
  TUESDAY: 'Martes',
  WEDNESDAY: 'Miércoles',
  THURSDAY: 'Jueves',
  FRIDAY: 'Viernes',
  SATURDAY: 'Sábado',
  SUNDAY: 'Domingo',
};

function getNextBookingDate(group: RecurringBookingGroup): string {
  const today = new Date().toISOString().slice(0, 10);
  const future = group.bookings
    .filter((b) => b.date >= today && b.status === 'CONFIRMED')
    .sort((a, b) => a.date.localeCompare(b.date));
  return future[0]?.date ?? '-';
}

function formatDate(dateStr: string): string {
  if (dateStr === '-') return '-';
  const [y, m, d] = dateStr.split('-');
  return `${d}/${m}/${y}`;
}

export function RecurringBookingListView() {
  const {
    setViewMode,
    recurringGroups,
    isRecurringGroupsLoading,
    cancelRecurringGroup,
    isCancellingRecurringGroup,
  } = useBooking();

  const [editingGroup, setEditingGroup] = useState<RecurringBookingGroup | null>(null);
  const [cancellingGroupId, setCancellingGroupId] = useState<string | null>(null);

  return (
    <>
      <section className="rounded-lg border bg-card/85 shadow-sm">
        <div className="flex flex-wrap items-center justify-between gap-4 border-b px-4 py-4">
          <div className="flex items-center gap-3">
            <Button
              type="button"
              variant="ghost"
              size="icon"
              className="rounded-full"
              onClick={() => setViewMode('panel')}
            >
              <ArrowLeft className="size-5" />
            </Button>
            <div>
              <h2 className="text-base font-semibold">Turnos fijos</h2>
              <p className="text-sm text-muted-foreground">
                {recurringGroups.length}{' '}
                {recurringGroups.length === 1 ? 'turno fijo' : 'turnos fijos'}
              </p>
            </div>
          </div>
        </div>

        {isRecurringGroupsLoading && (
          <div className="px-4 py-10 text-sm text-muted-foreground">Cargando turnos fijos...</div>
        )}

        {!isRecurringGroupsLoading && recurringGroups.length === 0 && (
          <div className="px-4 py-10 text-center text-sm text-muted-foreground">
            <Repeat className="mx-auto mb-3 size-10 opacity-40" />
            <p>No hay turnos fijos creados.</p>
          </div>
        )}

        {!isRecurringGroupsLoading && recurringGroups.length > 0 && (
          <div className="overflow-x-auto">
            <table className="hidden w-full sm:table">
              <thead>
                <tr className="border-b text-left text-xs font-medium uppercase tracking-wider text-muted-foreground">
                  <th className="px-4 py-3 font-medium">Cliente</th>
                  <th className="px-4 py-3 font-medium">Cancha</th>
                  <th className="px-4 py-3 font-medium">Día</th>
                  <th className="px-4 py-3 font-medium">Horario</th>
                  <th className="px-4 py-3 font-medium">Próxima fecha</th>
                  <th className="px-4 py-3 font-medium">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {recurringGroups.map((group) => {
                  const nextDate = getNextBookingDate(group);
                  return (
                    <tr key={group.id} className="transition-colors hover:bg-muted/50">
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2">
                          <User className="size-4 shrink-0 text-muted-foreground" />
                          <span className="truncate text-sm">{group.customerName || '-'}</span>
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2">
                          <MapPin className="size-4 shrink-0 text-muted-foreground" />
                          <span className="truncate text-sm">
                            {group.bookings[0]?.courtName ?? '-'}
                          </span>
                        </div>
                      </td>
                      <td className="px-4 py-4 text-sm">
                        {DAY_LABELS[group.dayOfWeek] ?? group.dayOfWeek}
                      </td>
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2">
                          <Clock className="size-4 shrink-0 text-muted-foreground" />
                          <span className="text-sm">
                            {group.startTime} - {group.endTime}
                          </span>
                        </div>
                      </td>
                      <td className="px-4 py-4 text-sm">{formatDate(nextDate)}</td>
                      <td className="px-4 py-4">
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={() => setEditingGroup(group)}
                            className="flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors hover:bg-muted"
                          >
                            <Pencil className="size-3.5" />
                            Editar
                          </button>
                          <button
                            type="button"
                            onClick={() => setCancellingGroupId(group.id)}
                            disabled={isCancellingRecurringGroup}
                            className="flex items-center gap-1.5 rounded-md border border-red-200 px-2.5 py-1.5 text-xs font-medium text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50"
                          >
                            <Trash2 className="size-3.5" />
                            Cancelar
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            <div className="divide-y sm:hidden">
              {recurringGroups.map((group) => {
                const nextDate = getNextBookingDate(group);
                return (
                  <div key={group.id} className="px-4 py-4">
                    <div className="mb-2 flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <User className="size-4 text-muted-foreground" />
                        <span className="text-sm font-semibold">{group.customerName || '-'}</span>
                      </div>
                      <span className="rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                        {DAY_LABELS[group.dayOfWeek]}
                      </span>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      {group.bookings[0]?.courtName} · {group.startTime} - {group.endTime}
                    </p>
                    <p className="mt-1 text-xs text-muted-foreground">
                      Próxima: {formatDate(nextDate)}
                    </p>
                    <div className="mt-2 flex gap-2">
                      <button
                        type="button"
                        onClick={() => setEditingGroup(group)}
                        className="flex items-center gap-1 rounded-md border px-2 py-1 text-xs transition-colors hover:bg-muted"
                      >
                        <Pencil className="size-3" />
                        Editar
                      </button>
                      <button
                        type="button"
                        onClick={() => setCancellingGroupId(group.id)}
                        disabled={isCancellingRecurringGroup}
                        className="flex items-center gap-1 rounded-md border border-red-200 px-2 py-1 text-xs text-red-600 transition-colors hover:bg-red-50 disabled:opacity-50"
                      >
                        <Trash2 className="size-3" />
                        Cancelar
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </section>

      <Dialog
        open={!!cancellingGroupId}
        onOpenChange={(open) => !open && setCancellingGroupId(null)}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Cancelar turno fijo</DialogTitle>
            <DialogDescription>
              ¿Estás seguro de cancelar este turno fijo? Se eliminarán todas las reservas futuras.
              Las reservas pasadas no se verán afectadas.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCancellingGroupId(null)}>
              Volver
            </Button>
            <Button
              variant="destructive"
              disabled={isCancellingRecurringGroup}
              onClick={() => {
                if (cancellingGroupId) {
                  cancelRecurringGroup(cancellingGroupId);
                  setCancellingGroupId(null);
                }
              }}
            >
              {isCancellingRecurringGroup ? 'Cancelando...' : 'Sí, cancelar turno fijo'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {editingGroup && (
        <RecurringBookingEditDialog
          group={editingGroup}
          open={!!editingGroup}
          onClose={() => setEditingGroup(null)}
        />
      )}
    </>
  );
}
