'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Download, TrendingUp, Users, DollarSign, AlertCircle } from 'lucide-react';
import { LineChart, Line, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { bookingsApi } from '@/lib/api';
import ActionButton from '@/components/ui/ActionButton';

const COLORS = ['#3b82f6', '#10b981', '#f59e0b'];

export default function ReportsPage() {
  const [dateRange, setDateRange] = useState('30');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  const getDateRange = () => {
    const end = new Date();
    end.setHours(23, 59, 59, 999);
    const start = new Date();
    
    switch (dateRange) {
      case '7':
        start.setDate(end.getDate() - 7);
        break;
      case '30':
        start.setDate(end.getDate() - 30);
        break;
      case '90':
        start.setDate(end.getDate() - 90);
        break;
      default:
        if (startDate && endDate) {
          return { startDate, endDate };
        }
    }
    
    return {
      startDate: start.toISOString().split('T')[0],
      endDate: end.toISOString().split('T')[0],
    };
  };

  const dates = getDateRange();

  // Fetch all bookings
  const { data: bookingsData, isLoading } = useQuery({
    queryKey: ['all-bookings'],
    queryFn: () => bookingsApi.getAll({ pageSize: 1000 }),
  });

  // Filter bookings by date range
  const bookings = Array.isArray(bookingsData?.items) 
    ? bookingsData.items.filter((b: any) => {
        const bookingDate = new Date(b.createdAt).toISOString().split('T')[0];
        return bookingDate >= dates.startDate && bookingDate <= dates.endDate;
      })
    : [];

  // Calculate metrics
  const totalRevenue = bookings.reduce((sum: number, b: any) => sum + (b.totalMinor || 0), 0);
  const totalBookings = bookings.length;
  const avgTicketPrice = totalBookings > 0 ? Math.round(totalRevenue / totalBookings) : 0;

  // Group by date for revenue chart
  const byDate = bookings.reduce((acc: Record<string, any>, b: any) => {
    const date = new Date(b.createdAt).toISOString().split('T')[0];
    if (!acc[date]) {
      acc[date] = { totalMinor: 0, count: 0 };
    }
    acc[date].totalMinor += b.totalMinor || 0;
    acc[date].count += 1;
    return acc;
  }, {} as Record<string, any>);

  const chartData = Object.entries(byDate)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([date, d]: [string, any]) => ({
      date: new Date(date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
      revenue: (d.totalMinor || 0) / 100,
      bookings: d.count || 0,
    }));

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Reports & Analytics</h1>
        <p className="text-muted-foreground mt-1">View detailed reports and performance metrics</p>
      </div>

      {/* Date Range Selector */}
      <div className="card">
        <div className="flex items-end gap-4 flex-wrap">
          <div>
            <label className="label">Date Range</label>
            <select
              className="input"
              value={dateRange}
              onChange={(e) => setDateRange(e.target.value)}
              disabled={isLoading}
            >
              <option value="7">Last 7 Days</option>
              <option value="30">Last 30 Days</option>
              <option value="90">Last 90 Days</option>
              <option value="custom">Custom Range</option>
            </select>
          </div>

          {dateRange === 'custom' && (
            <>
              <div>
                <label className="label">Start Date</label>
                <input 
                  type="date" 
                  className="input" 
                  value={startDate} 
                  onChange={(e) => setStartDate(e.target.value)}
                  disabled={isLoading}
                />
              </div>
              <div>
                <label className="label">End Date</label>
                <input 
                  type="date" 
                  className="input" 
                  value={endDate} 
                  onChange={(e) => setEndDate(e.target.value)}
                  disabled={isLoading}
                />
              </div>
            </>
          )}

          <ActionButton icon={Download} variant="secondary" disabled={isLoading}>
            Export
          </ActionButton>
        </div>
        {isLoading && (
          <p className="text-xs text-muted-foreground mt-2">Loading...</p>
        )}
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="card">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-muted-foreground text-sm font-medium">Total Revenue</p>
              <p className="text-2xl font-bold mt-2">ETB {Math.round(totalRevenue / 100).toLocaleString()}</p>
              <p className="text-xs text-muted-foreground mt-1">Last {dateRange} days</p>
            </div>
            <DollarSign className="h-8 w-8 text-blue-500 opacity-20" />
          </div>
        </div>

        <div className="card">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-muted-foreground text-sm font-medium">Total Bookings</p>
              <p className="text-2xl font-bold mt-2">{totalBookings.toLocaleString()}</p>
              <p className="text-xs text-muted-foreground mt-1">All bookings</p>
            </div>
            <Users className="h-8 w-8 text-green-500 opacity-20" />
          </div>
        </div>

        <div className="card">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-muted-foreground text-sm font-medium">Avg. Ticket Price</p>
              <p className="text-2xl font-bold mt-2">ETB {(avgTicketPrice / 100).toLocaleString()}</p>
              <p className="text-xs text-muted-foreground mt-1">Per booking</p>
            </div>
            <TrendingUp className="h-8 w-8 text-purple-500 opacity-20" />
          </div>
        </div>

        <div className="card">
          <div className="flex items-start justify-between">
            <div>
              <p className="text-muted-foreground text-sm font-medium">Avg. Daily Revenue</p>
              <p className="text-2xl font-bold mt-2">ETB {chartData.length > 0 ? Math.round((totalRevenue / 100) / chartData.length).toLocaleString() : '0'}</p>
              <p className="text-xs text-muted-foreground mt-1">Daily average</p>
            </div>
            <AlertCircle className="h-8 w-8 text-orange-500 opacity-20" />
          </div>
        </div>
      </div>

      {/* Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Revenue Trend */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4">Revenue Trend</h3>
          {chartData.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip formatter={(value: number) => `ETB ${Math.round(value).toLocaleString()}`} />
                <Legend />
                <Line type="monotone" dataKey="revenue" stroke="#3b82f6" dot={{ r: 5 }} activeDot={{ r: 7 }} strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[300px] flex items-center justify-center text-muted-foreground">
              No data available
            </div>
          )}
        </div>

        {/* Daily Bookings */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4">Daily Bookings</h3>
          {chartData.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} />
                <YAxis tick={{ fontSize: 12 }} />
                <Tooltip />
                <Bar dataKey="bookings" fill="#10b981" />
              </BarChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[300px] flex items-center justify-center text-muted-foreground">
              No data available
            </div>
          )}
        </div>

        {/* Booking Status Distribution */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4">Booking Status</h3>
          {bookings.length > 0 ? (
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={[
                    { name: 'Confirmed', value: bookings.filter((b: any) => b.status === 'CONFIRMED').length },
                    { name: 'Completed', value: bookings.filter((b: any) => b.status === 'COMPLETED').length },
                    { name: 'Cancelled', value: bookings.filter((b: any) => b.status === 'CANCELLED').length },
                    { name: 'Other', value: bookings.filter((b: any) => !['CONFIRMED', 'COMPLETED', 'CANCELLED'].includes(b.status)).length },
                  ].filter(d => d.value > 0)}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, value }) => `${name}: ${value}`}
                  outerRadius={100}
                  dataKey="value"
                >
                  {COLORS.map((color, idx) => <Cell key={idx} fill={color} />)}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          ) : (
            <div className="h-[300px] flex items-center justify-center text-muted-foreground">
              No data available
            </div>
          )}
        </div>

        {/* Top Payment Methods */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4">Payment Methods</h3>
          {bookings.length > 0 ? (
            <div className="space-y-3">
              {(Object.entries(
                bookings.reduce((acc: Record<string, number>, b: any) => {
                  const method = b.paymentIntent?.method || 'Unknown';
                  acc[method] = (acc[method] || 0) + 1;
                  return acc;
                }, {} as Record<string, number>)
              ) as [string, number][]
              )
                .sort(([, a], [, b]) => b - a)
                .slice(0, 5)
                .map(([method, count]) => (
                  <div key={method} className="flex justify-between items-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
                    <span className="text-sm capitalize">{method.toLowerCase().replace(/_/g, ' ')}</span>
                    <span className="font-semibold">{count}</span>
                  </div>
                ))}
            </div>
          ) : (
            <div className="h-[300px] flex items-center justify-center text-muted-foreground">
              No data available
            </div>
          )}
        </div>
      </div>

      {/* Summary Stats */}
      <div className="card">
        <h3 className="text-lg font-semibold mb-4">Summary</h3>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
            <p className="text-sm text-muted-foreground">Total Days with Bookings</p>
            <p className="text-xl font-bold mt-2">{chartData.length}</p>
          </div>
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
            <p className="text-sm text-muted-foreground">Confirmed Bookings</p>
            <p className="text-xl font-bold mt-2">{bookings.filter((b: any) => b.status === 'CONFIRMED').length}</p>
          </div>
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
            <p className="text-sm text-muted-foreground">Completed Bookings</p>
            <p className="text-xl font-bold mt-2">{bookings.filter((b: any) => b.status === 'COMPLETED').length}</p>
          </div>
          <div className="border border-gray-200 dark:border-gray-700 rounded-lg p-4">
            <p className="text-sm text-muted-foreground">Cancelled Bookings</p>
            <p className="text-xl font-bold mt-2">{bookings.filter((b: any) => b.status === 'CANCELLED').length}</p>
          </div>
        </div>
      </div>
    </div>
  );
}
