import React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CheckCircle, Download, Mail, Calendar, MapPin, Users } from 'lucide-react';
import Header from '@/components/Header';
import Footer from '@/components/Footer';

const OrderConfirmation = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const orderData = location.state?.orderData;

  if (!orderData) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <div className="container mx-auto px-4 pt-24 pb-12">
          <div className="text-center py-12">
            <h1 className="text-2xl font-bold mb-4">Orden no encontrada</h1>
            <Button onClick={() => navigate('/explore')}>
              Volver a Explorar
            </Button>
          </div>
        </div>
        <Footer />
      </div>
    );
  }

  const downloadReceipt = () => {
    const receiptData = {
      ...orderData,
      downloadDate: new Date().toISOString()
    };
    
    const dataStr = JSON.stringify(receiptData, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportFileDefaultName = `karibeo-receipt-${orderData.id}.json`;
    
    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      
      <div className="container mx-auto px-4 pt-24 pb-12">
        <div className="max-w-3xl mx-auto">
          {/* Success Header */}
          <div className="text-center mb-8">
            <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-12 h-12 text-green-600" />
            </div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              ¡Reserva Confirmada!
            </h1>
            <p className="text-gray-600">
              Tu reserva ha sido procesada exitosamente. Recibirás un email de confirmación en breve.
            </p>
          </div>

          {/* Order Details */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Calendar className="w-5 h-5" />
                  Detalles de la Reserva
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <span className="text-sm text-gray-600">Número de Orden:</span>
                  <p className="font-semibold">#{orderData.id}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Fecha de Reserva:</span>
                  <p className="font-semibold">
                    {new Date(orderData.date).toLocaleDateString('es-ES', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    })}
                  </p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Estado:</span>
                  <Badge className="ml-2 bg-green-100 text-green-800">
                    {orderData.status === 'confirmed' ? 'Confirmada' : orderData.status}
                  </Badge>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Mail className="w-5 h-5" />
                  Información de Contacto
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                <div>
                  <span className="text-sm text-gray-600">Nombre:</span>
                  <p className="font-semibold">
                    {orderData.customerInfo.firstName} {orderData.customerInfo.lastName}
                  </p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Email:</span>
                  <p className="font-semibold">{orderData.customerInfo.email}</p>
                </div>
                <div>
                  <span className="text-sm text-gray-600">Teléfono:</span>
                  <p className="font-semibold">{orderData.customerInfo.phone}</p>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Reserved Items */}
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>Reservas Confirmadas</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {orderData.items.map((item: any, index: number) => (
                  <div key={index} className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img
                      src={item.image}
                      alt={item.title}
                      className="w-20 h-20 object-cover rounded"
                    />
                    <div className="flex-1">
                      <h4 className="font-semibold">{item.title}</h4>
                      <div className="flex items-center text-gray-600 text-sm mt-1">
                        <MapPin className="w-4 h-4 mr-1" />
                        {item.location}
                      </div>
                      {item.selectedDate && (
                        <div className="flex items-center text-gray-600 text-sm mt-1">
                          <Calendar className="w-4 h-4 mr-1" />
                          Fecha: {item.selectedDate}
                        </div>
                      )}
                      {item.guests && (
                        <div className="flex items-center text-gray-600 text-sm mt-1">
                          <Users className="w-4 h-4 mr-1" />
                          {item.guests} personas
                        </div>
                      )}
                      <div className="flex justify-between items-center mt-2">
                        <span className="text-sm text-gray-600">
                          Cantidad: {item.quantity}
                        </span>
                        <span className="font-semibold text-primary">
                          ${(item.price * item.quantity).toFixed(2)}
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Payment Summary */}
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>Resumen de Pago</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span>Subtotal:</span>
                  <span>${orderData.pricing.subtotal.toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span>ITBIS (18%):</span>
                  <span>${orderData.pricing.taxes.toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span>Fee de servicio (5%):</span>
                  <span>${orderData.pricing.serviceFee.toFixed(2)}</span>
                </div>
                <hr className="my-2" />
                <div className="flex justify-between font-semibold text-lg">
                  <span>Total Pagado:</span>
                  <span className="text-primary">${orderData.pricing.total.toFixed(2)}</span>
                </div>
              </div>
              
              <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                <div className="flex items-center text-blue-800">
                  <CheckCircle className="w-5 h-5 mr-2" />
                  <span className="font-medium">
                    Pago procesado via {
                      orderData.paymentInfo.method === 'credit_card' ? 'Tarjeta de Crédito' : 
                      orderData.paymentInfo.method === 'paypal' ? 'PayPal' :
                      orderData.paymentInfo.method === 'bank_transfer' ? 'Transferencia Bancaria' :
                      'Efectivo'
                    }
                  </span>
                </div>
                {orderData.paymentInfo.paymentIntentId && (
                  <p className="text-xs text-blue-700 mt-2 font-mono">
                    ID de Transacción: {orderData.paymentInfo.paymentIntentId}
                  </p>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Special Requests */}
          {orderData.specialRequests && (
            <Card className="mb-6">
              <CardHeader>
                <CardTitle>Solicitudes Especiales</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-gray-700">{orderData.specialRequests}</p>
              </CardContent>
            </Card>
          )}

          {/* Action Buttons */}
          <div className="flex flex-col sm:flex-row gap-4 justify-center">
            <Button onClick={downloadReceipt} variant="outline">
              <Download className="w-4 h-4 mr-2" />
              Descargar Recibo
            </Button>
            <Button onClick={() => navigate('/explore')}>
              Explorar Más Ofertas
            </Button>
          </div>

          {/* Important Information */}
          <div className="mt-8 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
            <h3 className="font-semibold text-yellow-800 mb-2">Información Importante:</h3>
            <ul className="text-sm text-yellow-700 space-y-1">
              <li>• Recibirás un email de confirmación en los próximos 5 minutos</li>
              <li>• Política de cancelación: Gratuita hasta 24 horas antes</li>
              <li>• Para cambios o consultas, contacta al +1 (809) 123-4567</li>
              <li>• Guarda este número de orden para futuras referencias: #{orderData.id}</li>
            </ul>
          </div>
        </div>
      </div>

      <Footer />
    </div>
  );
};

export default OrderConfirmation;