'use client';

import { useQuery } from '@tanstack/react-query';
import { Ticket, Users, DollarSign, Percent } from 'lucide-react';
import StatCard from '@/components/dashboard/StatCard';
import DataTable from '@/components/ui/DataTable';
import Badge from '@/components/ui/Badge';
import { dashboardApi } from '@/lib/api/dashboard';
import { formatCurrency, formatDateTime } from '@/lib/utils';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';

const COLORS = ['#2563eb', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6'];

export default function DashboardPage() {
  const { data: stats, isLoading: statsLoading } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: dashboardApi.getStats,
  });

  const { data: revenueData, isLoading: revenueLoading } = useQuery({
    queryKey: ['revenue-chart'],
    queryFn: () => dashboardApi.getRevenueChart(30),
  });

  const { data: recentBookingsData, isLoading: bookingsLoading } = useQuery<any[]>({
    queryKey: ['recent-bookings'],
    queryFn: () => dashboardApi.getRecentBookings(10),
  });

  const { data: topAgents, isLoading: agentsLoading } = useQuery({
    queryKey: ['top-agents'],
    queryFn: () => dashboardApi.getTopAgents(5),
  });

  const { data: occupancyTrend, isLoading: occupancyLoading } = useQuery({
    queryKey: ['occupancy-trend'],
    queryFn: () => dashboardApi.getOccupancyTrend(7),
  });

  const { data: upcomingTrips, isLoading: tripsLoading } = useQuery({
    queryKey: ['upcoming-trips'],
    queryFn: () => dashboardApi.getUpcomingTrips(5),
  });

  const { data: paymentMethods } = useQuery({
    queryKey: ['payment-methods'],
    queryFn: dashboardApi.getPaymentMethods,
  });

  const recentBookings = Array.isArray(recentBookingsData) ? recentBookingsData : [];

  const bookingColumns = [
    { key: 'reference', label: 'Reference', render: (item: any) => item.bookingRef || item.reference },
    { 
      key: 'passenger', 
      label: 'Passenger', 
      render: (item: any) => {
        if (item.passenger?.fullName) {
          return item.passenger.fullName;
        }
        if (item.contactEmail) {
          return item.contactEmail;
        }
        if (item.contactPhone) {
          return item.contactPhone;
        }
        return 'N/A';
      }
    },
    { key: 'amount', label: 'Amount', render: (item: any) => formatCurrency(item.totalMinor || item.amount, item.currency || 'ETB') },
    {
      key: 'status',
      label: 'Status',
      render: (item: any) => (
        <Badge variant="status" status={item.status}>
          {item.status}
        </Badge>
      )
    },
    { key: 'createdAt', label: 'Created', render: (item: any) => formatDateTime(item.createdAt) },
  ];

  const agentColumns = [
    { key: 'name', label: 'Agent Name', render: (item: any) => item.name || item.fullName },
    { key: 'bookings', label: 'Bookings', render: (item: any) => item.bookingsCount || item.bookings || 0 },
    { key: 'revenue', label: 'Revenue', render: (item: any) => formatCurrency(item.totalRevenue || item.revenue || 0, 'ETB') },
    { key: 'commission', label: 'Commission', render: (item: any) => formatCurrency(item.commission || 0, 'ETB') },
  ];

  const tripColumns = [
    { key: 'trainName', label: 'Train', render: (item: any) => item.trainName || item.train?.name },
    { key: 'route', label: 'Route', render: (item: any) => `${item.originStation?.name || item.origin?.name} → ${item.destinationStation?.name || item.destination?.name}` },
    { key: 'departure', label: 'Departure', render: (item: any) => formatDateTime(item.departureAt) },
    { key: 'seats', label: 'Seats', render: (item: any) => `${item.availableSeats || 0}/${item.totalSeats || 0}` },
    {
      key: 'status',
      label: 'Status',
      render: (item: any) => (
        <Badge variant="status" status={item.status}>
          {item.status}
        </Badge>
      )
    },
  ];

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
        <p className="text-muted-foreground mt-1">Welcome back! Here&apos;s your operational summary.</p>
      </div>

      {/* Primary Metrics */}
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title="Total Bookings"
          value={statsLoading ? '...' : (stats?.totalBookings || 0).toLocaleString()}
          icon={Ticket}
          color="blue"
        />
        <StatCard
          title="Total Revenue"
          value={statsLoading ? '...' : formatCurrency(stats?.totalRevenue || 0, 'ETB')}
          icon={DollarSign}
          color="green"
        />
        <StatCard
          title="Total Passengers"
          value={statsLoading ? '...' : (stats?.totalPassengers || 0).toLocaleString()}
          icon={Users}
          color="purple"
        />
        <StatCard
          title="Occupancy Rate"
          value={statsLoading ? '...' : `${stats?.occupancyRate || 0}%`}
          icon={Percent}
          color="orange"
        />
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Revenue Trend */}
        {!revenueLoading && revenueData && revenueData.length > 0 && (
          <div className="card">
            <h2 className="mb-4 text-lg font-semibold text-foreground">Revenue Trend (Last 30 Days)</h2>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={revenueData}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} className="text-muted-foreground" />
                <YAxis tick={{ fontSize: 12 }} className="text-muted-foreground" />
                <Tooltip formatter={(value: number) => formatCurrency(value, 'ETB')} />
                <Line type="monotone" dataKey="revenue" stroke="#2563eb" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </div>
        )}

        {/* Occupancy Trend */}
        {!occupancyLoading && occupancyTrend && occupancyTrend.length > 0 && (
          <div className="card">
            <h2 className="mb-4 text-lg font-semibold text-foreground">Occupancy Trend (Last 7 Days)</h2>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={occupancyTrend}>
                <CartesianGrid strokeDasharray="3 3" className="stroke-border" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} className="text-muted-foreground" />
                <YAxis tick={{ fontSize: 12 }} className="text-muted-foreground" />
                <Tooltip formatter={(value: number) => `${value}%`} />
                <Bar dataKey="occupancyRate" fill="#10b981" radius={[8, 8, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        )}
      </div>

      {/* Payment Methods Distribution */}
      {paymentMethods && paymentMethods.length > 0 && (
        <div className="card">
          <h2 className="mb-4 text-lg font-semibold text-foreground">Payment Methods Distribution</h2>
          <ResponsiveContainer width="100%" height={300}>
            <PieChart>
              <Pie
                data={paymentMethods}
                dataKey="count"
                nameKey="method"
                cx="50%"
                cy="50%"
                outerRadius={80}
                label
              >
                {paymentMethods.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
          </ResponsiveContainer>
        </div>
      )}

      {/* Recent Bookings */}
      <div className="card">
        <h2 className="mb-4 text-lg font-semibold text-foreground">Recent Bookings</h2>
        <DataTable
          data={recentBookings}
          columns={bookingColumns}
          loading={bookingsLoading}
          emptyMessage="No recent bookings"
        />
      </div>

      {/* Upcoming Trips */}
      {upcomingTrips && upcomingTrips.length > 0 && (
        <div className="card">
          <h2 className="mb-4 text-lg font-semibold text-foreground">Upcoming Trips</h2>
          <DataTable
            data={upcomingTrips}
            columns={tripColumns}
            loading={tripsLoading}
            emptyMessage="No upcoming trips"
          />
        </div>
      )}

      {/* Top Agents */}
      {topAgents && topAgents.length > 0 && (
        <div className="card">
          <h2 className="mb-4 text-lg font-semibold text-foreground">Top Performing Agents</h2>
          <DataTable
            data={topAgents}
            columns={agentColumns}
            loading={agentsLoading}
            emptyMessage="No agent data"
          />
        </div>
      )}
    </div>
  );
}
