'use client';

export const dynamic = 'force-dynamic';

import { useRouter } from 'next/navigation';
import { useBookingStore } from '@/lib/booking-store';
import { useQuery, useMutation } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { useState, useEffect } from 'react';

import CustomModal from '@/components/CustomModal';

export default function SeatsPage() {
  const router = useRouter();
  const { selectedSchedule, passengers, setSeatHold, setPassengers, searchCriteria } = useBookingStore();
  const [selectedSeats, setSelectedSeats] = useState<string[]>([]);
  const [selectedCoach, setSelectedCoach] = useState<string | null>(null);
  const [_timeLeft, _setTimeLeft] = useState<number | null>(null);
  const [modalState, setModalState] = useState({
    isOpen: false,
    title: '',
    message: '',
    type: 'info' as 'warning' | 'error' | 'success' | 'info',
  });

  const { data: seatMapData, isLoading, error } = useQuery({
    queryKey: ['seatmap', selectedSchedule?.id],
    queryFn: () => apiClient.get(`/seats/seatmap/${selectedSchedule?.id}`),
    enabled: !!selectedSchedule?.id,
  });

  // Debug: Log the seat map data
  useEffect(() => {
    if (seatMapData) {
      console.log('Seat map data:', seatMapData);
      console.log('Is array?', Array.isArray(seatMapData));
      console.log('Has coaches?', (seatMapData as any)?.coaches);
    }
  }, [seatMapData]);

  const holdMutation = useMutation({
    mutationFn: async (seatIds: string[]) => {
      // Create temporary passenger IDs for the hold
      const passengersForHold = passengers.slice(0, seatIds.length).map((_, i) => ({
        passengerId: `temp-${Date.now()}-${i}`, // Temporary ID for guest booking
        seatId: seatIds[i],
      }));
      
      return apiClient.post(`/seats/hold`, {
        scheduleId: selectedSchedule?.id,
        originStationId: searchCriteria?.originStationId,
        destinationStationId: searchCriteria?.destinationStationId,
        passengers: passengersForHold,
      });
    },
    onSuccess: (data: any) => {
      setSeatHold({
        holdId: data.holdId || data.id,
        expiresAt: data.expiresAt,
      });
    },
  });

  // Extract coaches and seats from seat map data
  const coaches = (seatMapData as any)?.coaches || [];
  
  // Debug: Log coaches
  useEffect(() => {
    console.log('Coaches:', coaches);
    console.log('Selected seat class:', selectedSchedule?.selectedSeatClass);
    if (coaches.length > 0) {
      console.log('First coach structure:', coaches[0]);
      console.log('First coach seatClass:', coaches[0]?.seatClass);
      console.log('First coach coachClass:', coaches[0]?.coachClass);
    }
  }, [coaches, selectedSchedule?.selectedSeatClass]);
  
  // Filter coaches by selected seat class if available
  const filteredCoaches = selectedSchedule?.selectedSeatClass
    ? coaches.filter((c: any) => {
        // seatClass can be either a string or an object with a name property
        const seatClassName = typeof c.seatClass === 'string' ? c.seatClass : (c.seatClass?.name || c.coachClass || '');
        console.log('Comparing:', seatClassName, 'with', selectedSchedule.selectedSeatClass);
        return seatClassName === selectedSchedule.selectedSeatClass || 
               seatClassName.replace(/_/g, ' ').toLowerCase() === selectedSchedule.selectedSeatClass?.toLowerCase() ||
               seatClassName.toLowerCase() === selectedSchedule.selectedSeatClass?.toLowerCase();
      })
    : coaches;
  
  // Debug filtered coaches
  useEffect(() => {
    console.log('Filtered coaches:', filteredCoaches);
    console.log('Filtered coaches count:', filteredCoaches.length);
  }, [filteredCoaches]);
  
  const selectedCoachData = filteredCoaches.find((c: any) => c.id === selectedCoach);
  const seats = selectedCoachData?.seats || [];

  // Debug seats
  useEffect(() => {
    console.log('Selected coach data:', selectedCoachData);
    console.log('Seats:', seats);
    console.log('Seats count:', seats.length);
  }, [selectedCoachData, seats]);

  useEffect(() => {
    if (filteredCoaches && filteredCoaches.length > 0 && !selectedCoach) {
      setSelectedCoach(filteredCoaches[0].id);
    }
  }, [filteredCoaches, selectedCoach]);

  const toggleSeat = (seatId: string) => {
    if (selectedSeats.includes(seatId)) {
      setSelectedSeats(selectedSeats.filter(id => id !== seatId));
    } else if (selectedSeats.length < passengers.length) {
      setSelectedSeats([...selectedSeats, seatId]);
    }
  };

  const handleContinue = async () => {
    if (selectedSeats.length > 0) {
      await holdMutation.mutateAsync(selectedSeats);
      const updatedPassengers = passengers.map((p, i) => ({
        ...p,
        seatId: selectedSeats[i],
      }));
      setPassengers(updatedPassengers);
    }
    router.push('/booking/review');
  };

  const handleAutoAssign = async () => {
    const availableSeats = seats?.filter((s: any) => s.status === 'AVAILABLE') || [];
    if (availableSeats.length < passengers.length) {
      setModalState({
        isOpen: true,
        title: 'Not Enough Seats',
        message: `Only ${availableSeats.length} seat(s) available in this coach, but you need ${passengers.length} seat(s). Please select another coach.`,
        type: 'warning',
      });
      return;
    }
    
    const autoSelectedSeats = availableSeats.slice(0, passengers.length).map((s: any) => s.id);
    setSelectedSeats(autoSelectedSeats);
    
    try {
      await holdMutation.mutateAsync(autoSelectedSeats);
      const updatedPassengers = passengers.map((p, i) => ({
        ...p,
        seatId: autoSelectedSeats[i],
      }));
      setPassengers(updatedPassengers);
      router.push('/booking/review');
    } catch (error: any) {
      console.error('Failed to hold seats:', error);
      setModalState({
        isOpen: true,
        title: 'Seat Hold Failed',
        message: error?.response?.data?.message || 'Failed to hold seats. Please try again.',
        type: 'error',
      });
    }
  };

  if (!selectedSchedule || !passengers.length) {
    router.push('/booking/search');
    return null;
  }

  return (
    <>
      <CustomModal
        isOpen={modalState.isOpen}
        onClose={() => setModalState({ ...modalState, isOpen: false })}
        title={modalState.title}
        message={modalState.message}
        type={modalState.type}
      />
      <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">
          <h1 className="text-3xl font-bold mb-6 text-gray-900 dark:text-gray-100">Select Seats</h1>

          <div className="grid lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2">
              <div className="card mb-4">
                <h3 className="font-semibold mb-3 text-gray-900 dark:text-gray-100">Select Coach</h3>
                {selectedSchedule?.selectedSeatClassName && (
                  <div className="mb-3 text-sm text-gray-600 dark:text-gray-400">
                    Showing coaches for: <span className="font-semibold text-primary">{selectedSchedule.selectedSeatClassName.replace(/_/g, ' ')}</span>
                  </div>
                )}
                <div className="flex gap-2 overflow-x-auto pb-2">
                  {filteredCoaches?.map((coach: any) => {
                    const availableCount = coach.seats?.filter((s: any) => s.status === 'AVAILABLE').length || 0;
                    const seatClassName = typeof coach.seatClass === 'string' ? coach.seatClass : (coach.seatClass?.name || coach.coachClass || '');
                    return (
                      <button
                        key={coach.id}
                        onClick={() => setSelectedCoach(coach.id)}
                        className={`px-4 py-2 rounded whitespace-nowrap ${
                          selectedCoach === coach.id
                            ? 'bg-primary text-white'
                            : 'bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600'
                        }`}
                      >
                        <div>{coach.label || coach.name || coach.coachNumber}</div>
                        <div className="text-xs opacity-75">{seatClassName}</div>
                        <div className="text-xs opacity-75">{availableCount} available</div>
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="card">
                <h3 className="font-semibold mb-4 text-gray-900 dark:text-gray-100">Seat Map - {selectedCoachData?.name || selectedCoachData?.label || selectedCoachData?.coachNumber}</h3>
                {isLoading ? (
                  <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                    <p>Loading seats...</p>
                  </div>
                ) : error ? (
                  <div className="text-center py-8 text-red-500 dark:text-red-400">
                    <p>Error loading seats</p>
                    <p className="text-sm mt-2">{error?.message || 'Please try again'}</p>
                  </div>
                ) : seats.length === 0 ? (
                  <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                    <p>No seats available in this coach</p>
                    <p className="text-sm mt-2">Please select a different coach</p>
                  </div>
                ) : (
                  <>
                    {/* Seat Grid */}
                    <div className="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg mb-4 overflow-x-auto">
                      <div className="inline-grid gap-2" style={{ gridTemplateColumns: `repeat(4, minmax(0, 1fr))` }}>
                        {seats?.map((seat: any) => {
                          const seatLabel = seat.number || seat.label || seat.seatNumber || '?';
                          return (
                            <button
                              key={seat.id}
                              onClick={() => seat.status === 'AVAILABLE' && toggleSeat(seat.id)}
                              disabled={seat.status !== 'AVAILABLE'}
                              className={`w-12 h-12 rounded flex items-center justify-center text-xs font-semibold transition-all ${
                                selectedSeats.includes(seat.id)
                                  ? 'bg-primary text-white shadow-md scale-105'
                                  : seat.status === 'AVAILABLE'
                                  ? 'bg-green-100 dark:bg-green-900/40 hover:bg-green-200 dark:hover:bg-green-800/50 text-green-800 dark:text-green-200 hover:shadow-md'
                                  : seat.status === 'HELD'
                                  ? 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-700 dark:text-yellow-200 cursor-not-allowed opacity-75'
                                  : 'bg-gray-200 dark:bg-gray-700 text-gray-500 dark:text-gray-400 cursor-not-allowed opacity-60'
                              }`}
                              title={`Seat ${seatLabel} - ${seat.status}`}
                            >
                              {seatLabel}
                            </button>
                          );
                        })}
                      </div>
                    </div>

                    {/* Legend */}
                    <div className="flex flex-wrap gap-4 text-sm text-gray-700 dark:text-gray-300">
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 bg-green-100 dark:bg-green-900/40 rounded"></div>
                        <span>Available</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 bg-primary rounded"></div>
                        <span>Selected</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 bg-yellow-100 dark:bg-yellow-900/40 rounded"></div>
                        <span>Held</span>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 bg-gray-200 dark:bg-gray-700 rounded"></div>
                        <span>Booked</span>
                      </div>
                    </div>
                  </>
                )}
              </div>
            </div>

            <div>
              <div className="card sticky top-4">
                <h3 className="font-semibold mb-4 text-gray-900 dark:text-gray-100">Selection Summary</h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  Select {passengers.length} seat(s) for your passengers
                </p>
                <p className="text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100">
                  {selectedSeats.length} / {passengers.length} selected
                </p>

                <div className="space-y-2 mb-6">
                  {passengers.map((p, i) => {
                    const assignedSeat = selectedSeats[i] ? seats?.find((s: any) => s.id === selectedSeats[i]) : null;
                    const seatLabel = assignedSeat ? (assignedSeat.number || assignedSeat.label || assignedSeat.seatNumber || '-') : '-';
                    return (
                      <div key={i} className="flex justify-between text-sm text-gray-700 dark:text-gray-300">
                        <span>{p.name}</span>
                        <span className="font-medium">
                          {seatLabel}
                        </span>
                      </div>
                    );
                  })}
                </div>

                <button
                  onClick={handleContinue}
                  disabled={selectedSeats.length === 0}
                  className="btn-primary w-full mb-2"
                >
                  Continue with Selected Seats
                </button>
                <button 
                  onClick={handleAutoAssign}
                  disabled={holdMutation.isPending}
                  className="btn-secondary w-full"
                >
                  {holdMutation.isPending ? 'Assigning...' : 'Auto-Assign Seats'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      </div>
    </>
  );
}
