import React, { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Loader2, User, Mail, Phone, Calendar, Users, CreditCard, MapPin } from 'lucide-react';
import { Reservation } from '@/hooks/useChannelManager';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';

interface ReservationDetailsModalProps {
  open: boolean;
  onClose: () => void;
  reservation: Reservation | null;
  onCancel: (id: string, reason?: string) => Promise<boolean>;
}

export const ReservationDetailsModal: React.FC<ReservationDetailsModalProps> = ({ 
  open, 
  onClose, 
  reservation,
  onCancel 
}) => {
  const [loading, setLoading] = useState(false);
  const [showCancelForm, setShowCancelForm] = useState(false);
  const [cancelReason, setCancelReason] = useState('');

  if (!reservation) return null;

  const handleCancel = async () => {
    setLoading(true);
    const success = await onCancel(reservation.id, cancelReason);
    if (success) {
      setShowCancelForm(false);
      setCancelReason('');
      onClose();
    }
    setLoading(false);
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Detalles de la Reserva</DialogTitle>
          <DialogDescription>
            Información completa de la reserva #{reservation.id.slice(0, 8)}
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-6">
          {/* Status */}
          <div className="flex items-center justify-between">
            <div className="flex gap-2">
              <Badge variant={
                reservation.status === 'confirmed' ? 'default' :
                reservation.status === 'pending' ? 'secondary' :
                reservation.status === 'cancelled' ? 'destructive' : 'outline'
              }>
                {reservation.status}
              </Badge>
              <Badge variant={reservation.paymentStatus === 'paid' ? 'default' : 'secondary'}>
                {reservation.paymentStatus}
              </Badge>
            </div>
            <p className="text-sm text-muted-foreground">
              Canal: <span className="font-medium">{reservation.channel}</span>
            </p>
          </div>

          <Separator />

          {/* Guest Information */}
          <div className="space-y-3">
            <h3 className="font-semibold">Información del Huésped</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <User className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">{reservation.guestName}</span>
              </div>
              <div className="flex items-center gap-2">
                <Mail className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">{reservation.guestEmail}</span>
              </div>
              <div className="flex items-center gap-2">
                <Phone className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">{reservation.guestPhone}</span>
              </div>
            </div>
          </div>

          <Separator />

          {/* Booking Details */}
          <div className="space-y-3">
            <h3 className="font-semibold">Detalles de la Reserva</h3>
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <MapPin className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm font-medium">{reservation.listingName}</span>
              </div>
              <div className="flex items-center gap-2">
                <Calendar className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">
                  Check-in: {format(new Date(reservation.checkIn), 'dd/MM/yyyy HH:mm', { locale: es })}
                </span>
              </div>
              {reservation.checkOut && (
                <div className="flex items-center gap-2">
                  <Calendar className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm">
                    Check-out: {format(new Date(reservation.checkOut), 'dd/MM/yyyy HH:mm', { locale: es })}
                  </span>
                </div>
              )}
              <div className="flex items-center gap-2">
                <Users className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">{reservation.guests} huéspedes</span>
              </div>
            </div>
          </div>

          <Separator />

          {/* Payment Information */}
          <div className="space-y-3">
            <h3 className="font-semibold">Información de Pago</h3>
            <div className="flex items-center justify-between p-4 bg-muted rounded-lg">
              <div className="flex items-center gap-2">
                <CreditCard className="w-4 h-4 text-muted-foreground" />
                <span className="text-sm">Total</span>
              </div>
              <span className="text-2xl font-bold">${reservation.totalAmount.toLocaleString()}</span>
            </div>
          </div>

          {/* Special Requests */}
          {reservation.specialRequests && (
            <>
              <Separator />
              <div className="space-y-2">
                <h3 className="font-semibold">Solicitudes Especiales</h3>
                <p className="text-sm text-muted-foreground">{reservation.specialRequests}</p>
              </div>
            </>
          )}

          {/* Cancel Form */}
          {showCancelForm && reservation.status !== 'cancelled' && (
            <>
              <Separator />
              <div className="space-y-3">
                <Label htmlFor="cancel-reason">Motivo de Cancelación</Label>
                <Textarea
                  id="cancel-reason"
                  placeholder="Describe el motivo de la cancelación..."
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  rows={3}
                />
              </div>
            </>
          )}
        </div>

        <DialogFooter className="gap-2">
          <Button type="button" variant="outline" onClick={onClose}>
            Cerrar
          </Button>
          {reservation.status !== 'cancelled' && (
            showCancelForm ? (
              <>
                <Button 
                  type="button" 
                  variant="outline" 
                  onClick={() => setShowCancelForm(false)}
                  disabled={loading}
                >
                  Volver
                </Button>
                <Button 
                  type="button" 
                  variant="destructive" 
                  onClick={handleCancel}
                  disabled={loading}
                >
                  {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Confirmar Cancelación
                </Button>
              </>
            ) : (
              <Button 
                type="button" 
                variant="destructive" 
                onClick={() => setShowCancelForm(true)}
              >
                Cancelar Reserva
              </Button>
            )
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
