
'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { format, subDays, startOfMonth, endOfMonth, isWithinInterval } from 'date-fns';
import { es } from 'date-fns/locale';
import { Skeleton } from '@/components/ui/skeleton';
import { DollarSign, Film, TrendingUp, Users } from 'lucide-react';
import { apiClient } from '@/servicios/api-client';

type Reservation = {
    id: string;
    fecha_inicio: string;
    titulo_pelicula?: string;
    titulo_personalizado?: string;
    precio_total?: number;
};

const valueFormatter = (value: number) => `S/ ${value.toFixed(2)}`;

function CustomTooltip({ active, payload, label }: any) {
  if (active && payload && payload.length) {
    return (
      <div className="rounded-lg border bg-background p-2 shadow-sm">
        <div className="grid grid-cols-2 gap-2">
          <div className="flex flex-col space-y-1">
            <span className="text-[0.70rem] uppercase text-muted-foreground">
              Fecha
            </span>
            <span className="font-bold text-muted-foreground">
              {label}
            </span>
          </div>
          <div className="flex flex-col space-y-1">
            <span className="text-[0.70rem] uppercase text-muted-foreground">
              Ingresos
            </span>
            <span className="font-bold text-foreground">
              {valueFormatter(payload[0].value)}
            </span>
          </div>
        </div>
      </div>
    );
  }

  return null;
}

export function StatisticsAdminTab() {
    const [reservations, setReservations] = useState<Reservation[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    // Carga reservaciones al montar
    useEffect(() => {
        const loadReservations = async () => {
            try {
                setIsLoading(true);
                // TODO: Fetch reservations from API
                // const response = await apiClient.get<Reservation[]>('/reservaciones');
                // setReservations(response);
                setReservations([]);
            } catch (err) {
                setError(err instanceof Error ? err.message : 'Error desconocido');
            } finally {
                setIsLoading(false);
            }
        };
        loadReservations();
    }, []);

    const { weeklyData, monthlyStats, weeklyTotal } = (() => {
        if (!reservations || reservations.length === 0) {
            return { weeklyData: [], monthlyStats: {}, weeklyTotal: 0 };
        }

        // Weekly data for bar chart
        const today = new Date();
        const weeklyData = Array.from({ length: 7 }).map((_, i) => {
            const date = subDays(today, i);
            const formattedDate = format(date, 'MMM d', { locale: es });
            return { date: formattedDate, Ingresos: 0, fullDate: date };
        }).reverse();

        const dateMap = new Map(weeklyData.map(d => [format(d.fullDate, 'yyyy-MM-dd'), d]));

        // Monthly stats for cards
        const now = new Date();
        const monthStart = startOfMonth(now);
        const monthEnd = endOfMonth(now);
        
        let monthlyRevenue = 0;
        let mostBookedMovie: { title: string, count: number } = { title: 'N/A', count: 0 };
        const movieCounts: { [key: string]: number } = {};
        const monthlyReservations: Reservation[] = [];

        reservations.forEach(res => {
            const resDate = new Date(res.fecha_inicio);
            const resDateKey = format(resDate, 'yyyy-MM-dd');
            
            // Calculate weekly revenue
            if (dateMap.has(resDateKey)) {
                dateMap.get(resDateKey)!.Ingresos += res.precio_total || 0;
            }

            // Monthly calculations
            if (isWithinInterval(resDate, { start: monthStart, end: monthEnd })) {
                monthlyReservations.push(res);
                monthlyRevenue += res.precio_total || 0;
                const movie = res.titulo_pelicula || res.titulo_personalizado || 'Desconocido';
                movieCounts[movie] = (movieCounts[movie] || 0) + 1;
            }
        });

        if (Object.keys(movieCounts).length > 0) {
            const topMovie = Object.entries(movieCounts).sort((a, b) => b[1] - a[1])[0];
            mostBookedMovie = { title: topMovie[0], count: topMovie[1] };
        }
        
        const monthlyStats = {
            revenue: monthlyRevenue,
            reservationCount: monthlyReservations.length,
            averageTicket: monthlyReservations.length > 0 ? monthlyRevenue / monthlyReservations.length : 0,
            mostBookedMovie,
        };

        const weeklyTotal = weeklyData.reduce((acc, day) => acc + day.Ingresos, 0);

        return { weeklyData: Array.from(dateMap.values()).map(d => ({ date: d.date, Ingresos: d.Ingresos })), monthlyStats, weeklyTotal };

    })();
    
    if (isLoading) {
        return (
            <div className="space-y-6">
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                    {[...Array(4)].map((_, i) => (
                        <Card key={i}>
                            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                                <Skeleton className="h-5 w-24" />
                                <Skeleton className="h-6 w-6" />
                            </CardHeader>
                            <CardContent>
                                <Skeleton className="h-8 w-32" />
                                <Skeleton className="h-4 w-48 mt-2" />
                            </CardContent>
                        </Card>
                    ))}
                </div>
                <Card>
                    <CardHeader>
                        <Skeleton className="h-6 w-48" />
                        <Skeleton className="h-4 w-64" />
                    </CardHeader>
                    <CardContent>
                        <Skeleton className="w-full h-[350px]" />
                    </CardContent>
                </Card>
            </div>
        )
    }
    
    if (error) {
         return (
             <Card>
                <CardHeader>
                    <CardTitle>Estadísticas</CardTitle>
                    <CardDescription>Visualiza las métricas clave de la aplicación.</CardDescription>
                </CardHeader>
                <CardContent>
                    <p className="text-destructive">Error al cargar los datos: {error}</p>
                </CardContent>
            </Card>
         )
    }

    return (
        <div className="space-y-6">
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Ingresos Totales (Mes)</CardTitle>
                        <DollarSign className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{valueFormatter(monthlyStats.revenue || 0)}</div>
                        <p className="text-xs text-muted-foreground">Ingresos totales de este mes</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Reservas (Mes)</CardTitle>
                        <Users className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{monthlyStats.reservationCount || 0}</div>
                        <p className="text-xs text-muted-foreground">Total de reservas este mes</p>
                    </CardContent>
                </Card>
                 <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Ticket Promedio (Mes)</CardTitle>
                        <TrendingUp className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">{valueFormatter(monthlyStats.averageTicket || 0)}</div>
                        <p className="text-xs text-muted-foreground">Ingreso promedio por reserva</p>
                    </CardContent>
                </Card>
                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">Película Popular (Mes)</CardTitle>
                        <Film className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold line-clamp-1" title={monthlyStats.mostBookedMovie?.title}>{monthlyStats.mostBookedMovie?.title || 'N/A'}</div>
                        <p className="text-xs text-muted-foreground">{monthlyStats.mostBookedMovie?.count || 0} reservas</p>
                    </CardContent>
                </Card>
            </div>
             <Card>
                <CardHeader>
                    <CardTitle>Ingresos de los Últimos 7 Días</CardTitle>
                    <CardDescription>Total facturado por día.</CardDescription>
                     <div className="text-2xl font-bold pt-2">{valueFormatter(weeklyTotal)}</div>
                </CardHeader>
                <CardContent className="pl-2">
                   <ResponsiveContainer width="100%" height={350}>
                        <BarChart data={weeklyData}>
                            <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border) / 0.5)" />
                            <XAxis 
                                dataKey="date" 
                                stroke="#888888"
                                fontSize={12}
                                tickLine={false}
                                axisLine={false}
                            />
                            <YAxis 
                                stroke="#888888"
                                fontSize={12}
                                tickLine={false}
                                axisLine={false}
                                tickFormatter={(value) => `S/${value}`}
                            />
                            <Tooltip
                                content={<CustomTooltip />}
                                cursor={{ fill: 'hsl(var(--accent) / 0.1)' }}
                            />
                            <Bar dataKey="Ingresos" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} />
                        </BarChart>
                   </ResponsiveContainer>
                </CardContent>
            </Card>
        </div>
    );
}

