'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { seatsApi, schedulesApi } from '@/lib/api';
import Modal from '@/components/ui/Modal';
import ActionButton from '@/components/ui/ActionButton';
import Badge from '@/components/ui/Badge';
import { Search, Armchair, Lock, Unlock, ChevronRight } from 'lucide-react';

export default function SeatsPage() {
  const [search, setSearch] = useState('');
  const [selectedSchedule, setSelectedSchedule] = useState('');
  const [showBlockModal, setShowBlockModal] = useState(false);
  const [selectedSeat, setSelectedSeat] = useState<any>(null);
  const [blockReason, setBlockReason] = useState('');
  const queryClient = useQueryClient();

  const { data: schedulesData } = useQuery({
    queryKey: ['schedules'],
    queryFn: () => schedulesApi.getAll(),
  });

  const { data: seatMapData, isLoading } = useQuery({
    queryKey: ['seatmap', selectedSchedule],
    queryFn: () => selectedSchedule ? seatsApi.getSeatMap(selectedSchedule) : Promise.resolve(null),
    enabled: !!selectedSchedule,
  });

  const blockMutation = useMutation({
    mutationFn: ({ seatId, reason }: any) => seatsApi.block(seatId, { reason }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['seatmap'] });
      setShowBlockModal(false);
      setSelectedSeat(null);
      setBlockReason('');
    },
  });

  const unblockMutation = useMutation({
    mutationFn: (seatId: string) => seatsApi.unblock(seatId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['seatmap'] });
    },
  });

  const schedules = schedulesData?.items || schedulesData?.data || [];
  const coaches = seatMapData?.coaches || [];

  const handleBlock = (seat: any) => {
    setSelectedSeat(seat);
    setShowBlockModal(true);
  };

  const handleUnblock = async (seat: any) => {
    if (confirm('Are you sure you want to unblock this seat?')) {
      await unblockMutation.mutateAsync(seat.id);
    }
  };

  const submitBlock = async () => {
    if (!blockReason.trim()) {
      alert('Please provide a reason for blocking');
      return;
    }
    await blockMutation.mutateAsync({ seatId: selectedSeat.id, reason: blockReason });
  };

  const getSeatStatus = (seat: any) => {
    if (seat.status === 'BLOCKED' || seat.isBlocked) return 'BLOCKED';
    if (seat.status === 'BOOKED' || seat.isBooked) return 'BOOKED';
    if (seat.status === 'HELD') return 'HELD';
    return 'AVAILABLE';
  };

  const getSeatColor = (status: string) => {
    switch (status) {
      case 'AVAILABLE': return 'bg-green-500';
      case 'BOOKED': return 'bg-red-500';
      case 'HELD': return 'bg-yellow-500';
      case 'BLOCKED': return 'bg-gray-500';
      default: return 'bg-gray-300';
    }
  };

  const filteredCoaches = coaches.filter((coach: any) =>
    search ? coach.coachNumber?.toLowerCase().includes(search.toLowerCase()) : true
  );

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Seat Management</h1>
          <p className="text-muted-foreground mt-1">View and manage seat availability by schedule</p>
        </div>
      </div>

      <div className="card">
        <div className="flex items-center gap-4 mb-6">
          <div className="flex-1">
            <label className="label">Select Schedule</label>
            <select
              value={selectedSchedule}
              onChange={(e) => setSelectedSchedule(e.target.value)}
              className="input"
            >
              <option value="">Select a schedule...</option>
              {schedules.map((schedule: any) => {
                const trainNumber = schedule.train?.trainNumber || schedule.train?.name || 'N/A';
                const routeName = schedule.route?.name || 'N/A';
                const date = schedule.departureAt ? new Date(schedule.departureAt).toLocaleDateString() : 'N/A';
                return (
                  <option key={schedule.id} value={schedule.id}>
                    {trainNumber} - {routeName} - {date}
                  </option>
                );
              })}
            </select>
          </div>
          <div className="relative flex-1">
            <label className="label">Search Coaches</label>
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <input
                type="text"
                placeholder="Search by coach number..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="input pl-10"
              />
            </div>
          </div>
        </div>

        {!selectedSchedule ? (
          <div className="text-center py-12 text-muted-foreground">
            <Armchair className="h-12 w-12 mx-auto mb-3 opacity-50" />
            <p>Select a schedule to view seat map</p>
          </div>
        ) : isLoading ? (
          <div className="text-center py-12">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
            <p className="text-muted-foreground mt-3">Loading seats...</p>
          </div>
        ) : filteredCoaches.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <p>No coaches found for this schedule</p>
          </div>
        ) : (
          <div className="space-y-6">
            {/* Legend */}
            <div className="flex items-center gap-6 p-4 bg-muted/50 rounded-lg">
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 rounded bg-green-500"></div>
                <span className="text-sm">Available</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 rounded bg-red-500"></div>
                <span className="text-sm">Booked</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 rounded bg-yellow-500"></div>
                <span className="text-sm">Held</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 rounded bg-gray-500"></div>
                <span className="text-sm">Blocked</span>
              </div>
            </div>

            {/* Coaches */}
            {filteredCoaches.map((coach: any) => {
              const seats = coach.seats || [];
              const seatClass = coach.seatClass?.name || 'N/A';
              const availableCount = seats.filter((s: any) => getSeatStatus(s) === 'AVAILABLE').length;
              const bookedCount = seats.filter((s: any) => getSeatStatus(s) === 'BOOKED').length;
              const blockedCount = seats.filter((s: any) => getSeatStatus(s) === 'BLOCKED').length;

              return (
                <div key={coach.id} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-4">
                    <div>
                      <h3 className="text-lg font-semibold">
                        Coach {coach.coachNumber} - {coach.label}
                      </h3>
                      <p className="text-sm text-muted-foreground">
                        {seatClass} • {seats.length} seats
                      </p>
                    </div>
                    <div className="flex gap-3 text-sm">
                      <span className="text-green-600">Available: {availableCount}</span>
                      <span className="text-red-600">Booked: {bookedCount}</span>
                      <span className="text-gray-600">Blocked: {blockedCount}</span>
                    </div>
                  </div>

                  <div className="grid grid-cols-8 gap-2">
                    {seats.map((seat: any) => {
                      const status = getSeatStatus(seat);
                      const color = getSeatColor(status);
                      const canBlock = status === 'AVAILABLE';
                      const canUnblock = status === 'BLOCKED';

                      return (
                        <div
                          key={seat.id}
                          className="relative group"
                        >
                          <div
                            className={`${color} text-white rounded-lg p-2 text-center text-sm font-medium cursor-pointer hover:opacity-80 transition-opacity`}
                            title={`${seat.seatNumber} - ${status}`}
                          >
                            {seat.seatNumber}
                          </div>
                          {(canBlock || canUnblock) && (
                            <div className="absolute inset-0 bg-black/60 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1">
                              {canBlock && (
                                <button
                                  onClick={() => handleBlock(seat)}
                                  className="p-1 bg-white rounded hover:bg-gray-100"
                                  title="Block seat"
                                >
                                  <Lock className="h-3 w-3 text-gray-700" />
                                </button>
                              )}
                              {canUnblock && (
                                <button
                                  onClick={() => handleUnblock(seat)}
                                  className="p-1 bg-white rounded hover:bg-gray-100"
                                  title="Unblock seat"
                                >
                                  <Unlock className="h-3 w-3 text-gray-700" />
                                </button>
                              )}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Block Modal */}
      <Modal
        isOpen={showBlockModal}
        onClose={() => {
          setShowBlockModal(false);
          setSelectedSeat(null);
          setBlockReason('');
        }}
        title="Block Seat"
        size="md"
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Block seat <strong>{selectedSeat?.seatNumber}</strong> in Coach{' '}
            <strong>{selectedSeat?.coach?.coachNumber}</strong>
          </p>
          <div>
            <label className="label">Reason for Blocking *</label>
            <textarea
              className="input"
              rows={3}
              value={blockReason}
              onChange={(e) => setBlockReason(e.target.value)}
              placeholder="e.g., Maintenance required, Damaged seat, Reserved for staff"
            />
          </div>
          <div className="flex justify-end gap-2">
            <ActionButton
              variant="secondary"
              onClick={() => {
                setShowBlockModal(false);
                setSelectedSeat(null);
                setBlockReason('');
              }}
            >
              Cancel
            </ActionButton>
            <ActionButton
              onClick={submitBlock}
              loading={blockMutation.isPending}
              disabled={!blockReason.trim()}
            >
              Block Seat
            </ActionButton>
          </div>
        </div>
      </Modal>
    </div>
  );
}
