'use client';

export const dynamic = 'force-dynamic';

import { useRouter } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { useMutation, useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useEffect, useState, useRef } from 'react';
import { CheckCircle, Download, Share2, Copy, Printer, Mail, Train, FileText } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
import { format } from 'date-fns';

type BookingWithTicket = {
  id: string;
  pnr?: string | null;
  status?: string;
  totalMinor?: number;
  ticket?: {
    barcodePayload?: string;
    qrPayload?: string;
  };
};

export default function ConfirmationPage() {
  const router = useRouter();
  const { bookingId, pnr, selectedSchedule, passengers, clearBooking } = useBookingStore();
  const [copied, setCopied] = useState(false);
  const [isGeneratingVoucher, setIsGeneratingVoucher] = useState(false);
  const confirmAttempted = useRef(false);

  const confirmMutation = useMutation({
    mutationFn: () => apiClient.patch(`/bookings/${bookingId}/confirm`, { status: 'SUCCEEDED' }),
  });

  const { data: _booking } = useQuery<BookingWithTicket>({
    queryKey: ['booking', bookingId],
    queryFn: async (): Promise<BookingWithTicket> => {
      try {
        return await apiClient.get(`/bookings/${bookingId}`);
      } catch (error) {
        console.log('Booking API not available, using local data');
        return {
          id: bookingId || '',
          pnr: pnr || undefined,
          status: 'CONFIRMED',
          totalMinor: passengers.reduce((sum) => sum + (selectedSchedule?.baseFareAdult || 0), 0),
        };
      }
    },
    enabled: !!bookingId,
  });

  useEffect(() => {
    if (bookingId && !confirmAttempted.current) {
      confirmAttempted.current = true;
      confirmMutation.mutate();
      
      apiClient.post(`/tickets/generate/${bookingId}`).catch((err) => {
        console.error('Failed to generate ticket:', err);
      });
    }
  }, [bookingId, confirmMutation]);

  const copyPNR = () => {
    if (pnr) {
      navigator.clipboard.writeText(pnr);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleDownloadVoucher = async () => {
    if (!_booking || !pnr) {
      alert('Booking data not available. Please try again.');
      return;
    }

    setIsGeneratingVoucher(true);
    try {
      console.log('📄 Generating voucher with data:', { _booking, pnr, selectedSchedule, passengers });
      
      const { generateVoucherPDF } = await import('@/lib/generate-voucher');
      
      const voucherData = {
        bookingRef: pnr,
        status: _booking.status || 'CONFIRMED',
        passengers: passengers.map(p => ({
          fullName: p.name,
          category: 'ADULT',
          seat: p.seatNumber ? {
            number: p.seatNumber,
            coach: 'N/A',
            seatClass: selectedSchedule?.selectedSeatClassName || 'Standard',
          } : undefined,
        })),
        schedule: {
          trainNumber: selectedSchedule?.trainNumber || 'N/A',
          trainName: 'EDR Express',
          origin: {
            name: selectedSchedule?.origin || 'Origin',
            code: 'ORG',
            city: selectedSchedule?.origin || 'Origin',
          },
          destination: {
            name: selectedSchedule?.destination || 'Destination',
            code: 'DST',
            city: selectedSchedule?.destination || 'Destination',
          },
          departureAt: selectedSchedule?.departureTime || new Date().toISOString(),
          arrivalAt: selectedSchedule?.arrivalTime || new Date().toISOString(),
        },
        totalMinor: _booking.totalMinor || passengers.reduce((sum) => sum + (selectedSchedule?.baseFareAdult || 0), 0),
        currency: 'ETB',
        bookingType: 'ONE_WAY',
        createdAt: new Date().toISOString(),
      };

      console.log('📄 Voucher data prepared:', voucherData);
      await generateVoucherPDF(voucherData);
      console.log('✅ Voucher generated successfully');
    } catch (error) {
      console.error('❌ Failed to generate voucher:', error);
      alert(`Failed to generate voucher: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsGeneratingVoucher(false);
    }
  };

  const handlePrintTickets = () => {
    window.print();
  };

  const handleEmailTickets = () => {
    alert('Tickets have been sent to your registered email address.');
  };

  const handleNewBooking = () => {
    clearBooking();
    router.push('/booking/search');
  };

  useEffect(() => {
    if (!bookingId || !pnr) {
      router.push('/booking/search');
    }
  }, [bookingId, pnr, router]);

  if (!bookingId || !pnr) return null;

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
      <div className="container mx-auto px-4">
        <div className="max-w-6xl mx-auto">
          {/* Success Header */}
          <div className="text-center mb-8">
            <div className="flex justify-center mb-4">
              <div className="w-20 h-20 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center animate-bounce">
                <CheckCircle className="w-12 h-12 text-green-600 dark:text-green-400" />
              </div>
            </div>
            <h1 className="text-4xl font-bold text-green-600 dark:text-green-400 mb-2">Booking confirmed!</h1>
            <p className="text-gray-600 dark:text-gray-400 text-lg">Your train tickets are ready</p>
          </div>

          {/* PNR Card */}
          <div className="card mb-6 bg-gradient-to-r from-primary to-primary-600 dark:from-primary-700 dark:to-primary-900 text-white">
            <div className="text-center">
              <p className="text-sm opacity-90 mb-2">Booking reference (PNR)</p>
              <div className="flex items-center justify-center gap-3">
                <span className="text-5xl font-bold tracking-widest">{pnr}</span>
                <button 
                  onClick={copyPNR} 
                  className="p-2 hover:bg-white hover:bg-opacity-20 rounded transition-colors"
                  title="Copy PNR"
                >
                  {copied ? (
                    <CheckCircle className="w-6 h-6" />
                  ) : (
                    <Copy className="w-6 h-6" />
                  )}
                </button>
              </div>
              <p className="text-sm opacity-90 mt-2">Save this reference number for future use</p>
            </div>
          </div>

          {/* Trip Summary with QR Code */}
          <div className="card mb-6">
            <div className="flex flex-col md:flex-row gap-6">
              {/* QR Code Section */}
              <div className="flex flex-col items-center justify-center bg-gray-50 dark:bg-gray-800 rounded-lg p-6 md:w-48 flex-shrink-0">
                <QRCodeSVG
                  value={pnr}
                  size={160}
                  level="H"
                  includeMargin={true}
                />
                <p className="text-xs text-gray-600 dark:text-gray-400 mt-2 text-center font-semibold">Scan at gate</p>
              </div>

              {/* Trip Details */}
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 bg-primary-100 dark:bg-primary-900/30 rounded-lg flex items-center justify-center">
                    <Train className="w-6 h-6 text-primary dark:text-primary-400" />
                  </div>
                  <h2 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">Trip details</h2>
                </div>
                <div className="grid md:grid-cols-2 gap-4">
                  <div className="space-y-3">
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Train number</p>
                      <p className="font-semibold text-lg text-gray-900 dark:text-gray-100">{selectedSchedule?.trainNumber}</p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Route</p>
                      <p className="font-semibold text-lg text-gray-900 dark:text-gray-100">{selectedSchedule?.origin} → {selectedSchedule?.destination}</p>
                    </div>
                    {selectedSchedule?.selectedSeatClassName && (
                      <div>
                        <p className="text-sm text-gray-600 dark:text-gray-400">Class</p>
                        <p className="font-semibold text-gray-900 dark:text-gray-100">{selectedSchedule.selectedSeatClassName.replace(/_/g, ' ')}</p>
                      </div>
                    )}
                  </div>
                  <div className="space-y-3">
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Departure</p>
                      <p className="font-semibold text-gray-900 dark:text-gray-100">
                        {selectedSchedule?.departureTime && format(new Date(selectedSchedule.departureTime), 'PPp')}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Arrival</p>
                      <p className="font-semibold text-gray-900 dark:text-gray-100">
                        {selectedSchedule?.arrivalTime && format(new Date(selectedSchedule.arrivalTime), 'PPp')}
                      </p>
                    </div>
                    <div>
                      <p className="text-sm text-gray-600 dark:text-gray-400">Duration</p>
                      <p className="font-semibold text-gray-900 dark:text-gray-100">{selectedSchedule?.duration}</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Tickets */}
          <div className="mb-6">
            <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-gray-100">Your tickets</h2>
            <div className="space-y-4">
              {passengers.map((passenger, index) => {
                const backendTicket = _booking?.ticket || null;
                const ticketNumber = backendTicket?.barcodePayload || `TKT-${bookingId?.slice(0, 8).toUpperCase()}-${(index + 1).toString().padStart(2, '0')}`;

                return (
                  <div key={index} className="card hover:shadow-lg transition-shadow">
                    {/* Ticket Info */}
                    <div className="flex-1">
                      <div className="flex items-start justify-between mb-4">
                        <div>
                          <h3 className="text-xl font-bold text-gray-900 dark:text-gray-100">{passenger.name}</h3>
                          <p className="text-sm text-gray-600 dark:text-gray-400">Passenger {index + 1}</p>
                        </div>
                        <span className="badge badge-success">CONFIRMED</span>
                      </div>
                      
                      <div className="grid grid-cols-2 gap-4 text-sm">
                        <div>
                          <p className="text-gray-600 dark:text-gray-400">Ticket Number</p>
                          <p className="font-semibold text-gray-900 dark:text-gray-100">{ticketNumber}</p>
                        </div>
                        <div>
                          <p className="text-gray-600 dark:text-gray-400">Date of Birth</p>
                          <p className="font-semibold text-gray-900 dark:text-gray-100">{format(new Date(passenger.dateOfBirth), 'PP')}</p>
                        </div>
                        <div>
                          <p className="text-gray-600 dark:text-gray-400">Nationality</p>
                          <p className="font-semibold text-gray-900 dark:text-gray-100">{passenger.nationality}</p>
                        </div>
                        <div>
                          <p className="text-gray-600 dark:text-gray-400">Seat</p>
                          <p className="font-semibold text-gray-900 dark:text-gray-100">{passenger.seatNumber || 'Will be assigned'}</p>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="grid grid-cols-2 md:grid-cols-5 gap-3 mb-6">
            <button 
              onClick={handleDownloadVoucher}
              disabled={isGeneratingVoucher}
              className="btn-primary flex items-center justify-center gap-2 relative"
            >
              {isGeneratingVoucher ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  <span className="hidden sm:inline">Generating...</span>
                </>
              ) : (
                <>
                  <FileText className="w-4 h-4" />
                  <span className="hidden sm:inline">Download Voucher</span>
                  <span className="sm:hidden">Voucher</span>
                </>
              )}
            </button>
            <button 
              onClick={handlePrintTickets}
              className="btn-secondary flex items-center justify-center gap-2"
            >
              <Printer className="w-4 h-4" />
              <span className="hidden sm:inline">Print</span>
            </button>
            <button 
              onClick={handleEmailTickets}
              className="btn-secondary flex items-center justify-center gap-2"
            >
              <Mail className="w-4 h-4" />
              <span className="hidden sm:inline">Email</span>
            </button>
            <button 
              onClick={() => alert('Tickets download will be available soon.')}
              className="btn-secondary flex items-center justify-center gap-2"
            >
              <Download className="w-4 h-4" />
              <span className="hidden sm:inline">Download</span>
            </button>
            <button className="btn-secondary flex items-center justify-center gap-2">
              <Share2 className="w-4 h-4" />
              <span className="hidden sm:inline">Share</span>
            </button>
          </div>

          {/* New Booking Button */}
          <button 
            onClick={handleNewBooking} 
            className="btn-primary w-full py-4 text-lg font-semibold"
          >
            Book another trip
          </button>

          {/* Info Notices */}
          <div className="mt-6 space-y-3">
            <div className="p-4 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg">
              <p className="text-sm text-blue-800 dark:text-blue-300">
                📧 A confirmation email with your tickets has been sent to your registered email address.
              </p>
            </div>
            <div className="p-4 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-800 rounded-lg">
              <p className="text-sm text-green-800 dark:text-green-300">
                ✅ Please arrive at the station at least 30 minutes before departure.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
