'use client';

import { useQuery } from '@tanstack/react-query';
import { Train, MapPin, Users, Clock } from 'lucide-react';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import { liveApi } from '@/lib/api';
import { formatDateTime } from '@/lib/utils';

export default function LiveTrackingPage() {
  const { data: trips, isLoading } = useQuery({
    queryKey: ['live-trips'],
    queryFn: liveApi.getTrips,
    refetchInterval: 30000,
  });

  const { data: crowdSignals } = useQuery({
    queryKey: ['crowd-signals'],
    queryFn: liveApi.getCrowdSignals,
    refetchInterval: 60000,
  });

  const tripsArray = Array.isArray(trips) ? trips : (trips as any)?.items || [];
  const signalsArray = Array.isArray(crowdSignals) ? crowdSignals : (crowdSignals as any)?.items || [];

  const columns = [
    {
      key: 'train',
      label: 'Train',
      render: (trip: any) => (
        <div className="flex items-center gap-2">
          <Train className="h-4 w-4 text-emerald-600 shrink-0" />
          <div>
            <div className="font-medium">{trip.schedule?.train?.name || trip.trainName || 'N/A'}</div>
            <div className="text-xs text-muted-foreground font-mono">{trip.schedule?.train?.number || trip.trainNumber || ''}</div>
          </div>
        </div>
      ),
    },
    {
      key: 'route',
      label: 'Route',
      render: (trip: any) => (
        <div className="text-sm">
          <div>{trip.schedule?.originStation?.name || trip.origin || 'N/A'}</div>
          <div className="text-muted-foreground">→ {trip.schedule?.destinationStation?.name || trip.destination || 'N/A'}</div>
        </div>
      ),
    },
    {
      key: 'location',
      label: 'Location',
      render: (trip: any) => (
        <div className="flex items-center gap-1 text-sm">
          <MapPin className="h-3 w-3 text-muted-foreground shrink-0" />
          <span>{trip.currentStation?.name || trip.lastKnownStation || 'En route'}</span>
        </div>
      ),
    },
    {
      key: 'departure',
      label: 'Departure',
      render: (trip: any) => (
        <span className="text-sm font-mono">
          {trip.schedule?.departureAt ? formatDateTime(trip.schedule.departureAt) : 'N/A'}
        </span>
      ),
    },
    {
      key: 'passengers',
      label: 'Passengers',
      render: (trip: any) => (
        <div className="flex items-center gap-1">
          <Users className="h-3 w-3 text-muted-foreground" />
          <span className="text-sm">{trip.passengerCount ?? trip.bookedSeats ?? '—'}</span>
        </div>
      ),
    },
    {
      key: 'status',
      label: 'Status',
      render: (trip: any) => (
        <Badge variant="status" status={
          trip.status === 'EN_ROUTE' ? 'CONFIRMED' :
          trip.status === 'DELAYED' ? 'PENDING' :
          trip.status === 'CANCELLED' ? 'CANCELLED' : 'CONFIRMED'
        }>
          {(trip.status || 'SCHEDULED').replace(/_/g, ' ')}
        </Badge>
      ),
    },
    {
      key: 'delay',
      label: 'Delay',
      render: (trip: any) => {
        const delay = trip.delayMinutes ?? trip.delay;
        if (!delay) return <span className="text-sm text-emerald-600">On time</span>;
        return (
          <div className="flex items-center gap-1 text-amber-600">
            <Clock className="h-3 w-3" />
            <span className="text-sm font-medium">+{delay} min</span>
          </div>
        );
      },
    },
  ];

  const crowdColumns = [
    {
      key: 'station',
      label: 'Station',
      render: (s: any) => <span className="font-medium">{s.station?.name || s.stationName || 'N/A'}</span>,
    },
    {
      key: 'level',
      label: 'Crowd Level',
      render: (s: any) => (
        <Badge variant="status" status={
          s.level === 'HIGH' || s.crowdLevel === 'HIGH' ? 'CANCELLED' :
          s.level === 'MEDIUM' || s.crowdLevel === 'MEDIUM' ? 'PENDING' : 'CONFIRMED'
        }>
          {s.level || s.crowdLevel || 'LOW'}
        </Badge>
      ),
    },
    {
      key: 'count',
      label: 'Estimated Count',
      render: (s: any) => <span className="text-sm">{s.estimatedCount ?? s.count ?? '—'}</span>,
    },
    {
      key: 'updatedAt',
      label: 'Last Updated',
      render: (s: any) => <span className="text-sm text-muted-foreground">{s.updatedAt ? formatDateTime(s.updatedAt) : 'N/A'}</span>,
    },
  ];

  const enRoute = tripsArray.filter((t: any) => t.status === 'EN_ROUTE' || t.status === 'BOARDING').length;
  const delayed = tripsArray.filter((t: any) => t.delayMinutes > 0 || t.delay > 0).length;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-foreground">Live Tracking</h1>
        <p className="text-muted-foreground">Real-time train tracking and station crowd signals</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="card">
          <p className="text-sm text-muted-foreground">Active Trips</p>
          <p className="text-2xl font-bold mt-1">{tripsArray.length}</p>
        </div>
        <div className="card">
          <p className="text-sm text-muted-foreground">En Route / Boarding</p>
          <p className="text-2xl font-bold mt-1 text-emerald-600">{enRoute}</p>
        </div>
        <div className="card">
          <p className="text-sm text-muted-foreground">Delayed</p>
          <p className="text-2xl font-bold mt-1 text-amber-600">{delayed}</p>
        </div>
      </div>

      <div className="card">
        <h2 className="text-lg font-semibold mb-4">Active Trips</h2>
        <DataTable
          data={tripsArray}
          columns={columns}
          loading={isLoading}
          emptyMessage="No active trips found"
        />
      </div>

      {signalsArray.length > 0 && (
        <div className="card">
          <h2 className="text-lg font-semibold mb-4">Station Crowd Signals</h2>
          <DataTable
            data={signalsArray}
            columns={crowdColumns}
            loading={false}
            emptyMessage="No crowd signals"
          />
        </div>
      )}
    </div>
  );
}
