import { useState } from 'react';
import DashboardLayout from '@/components/DashboardLayout';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useAnalytics } from '@/hooks/useAnalytics';
import { TrendingUp, Users, DollarSign, MapPin, Loader2 } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';

const Analytics = () => {
  const [period, setPeriod] = useState('month');
  const { analytics, loading, error, refetch } = useAnalytics(period);

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('es-DO', {
      style: 'currency',
      currency: 'DOP',
    }).format(amount);
  };

  const StatCard = ({ 
    title, 
    value, 
    icon: Icon, 
    description 
  }: { 
    title: string; 
    value: string | number; 
    icon: any; 
    description?: string;
  }) => (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <CardTitle className="text-sm font-medium">{title}</CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        {description && (
          <p className="text-xs text-muted-foreground mt-1">{description}</p>
        )}
      </CardContent>
    </Card>
  );

  return (
    <DashboardLayout>
      <div className="p-6 space-y-6">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold">Analytics</h1>
            <p className="text-muted-foreground mt-1">
              Métricas y estadísticas de tu plataforma
            </p>
          </div>
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-40">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="day">Hoy</SelectItem>
              <SelectItem value="week">Esta Semana</SelectItem>
              <SelectItem value="month">Este Mes</SelectItem>
              <SelectItem value="year">Este Año</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {/* Loading State */}
        {loading && (
          <div className="space-y-6">
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              {[1, 2, 3, 4].map((i) => (
                <Card key={i}>
                  <CardHeader>
                    <Skeleton className="h-4 w-24" />
                  </CardHeader>
                  <CardContent>
                    <Skeleton className="h-8 w-32" />
                  </CardContent>
                </Card>
              ))}
            </div>
            <div className="grid gap-4 md:grid-cols-2">
              <Card>
                <CardHeader>
                  <Skeleton className="h-6 w-40" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-64 w-full" />
                </CardContent>
              </Card>
              <Card>
                <CardHeader>
                  <Skeleton className="h-6 w-40" />
                </CardHeader>
                <CardContent>
                  <Skeleton className="h-64 w-full" />
                </CardContent>
              </Card>
            </div>
          </div>
        )}

        {/* Error State */}
        {error && (
          <Card className="border-destructive">
            <CardContent className="pt-6">
              <div className="text-center space-y-4">
                <p className="text-destructive">{error}</p>
                <button
                  onClick={refetch}
                  className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
                >
                  Reintentar
                </button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Analytics Data */}
        {analytics && !loading && (
          <>
            {/* Stats Grid */}
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
              <StatCard
                title="Total Usuarios"
                value={analytics.totalUsers.toLocaleString()}
                icon={Users}
                description="Usuarios registrados"
              />
              <StatCard
                title="Ingresos Totales"
                value={formatCurrency(analytics.totalRevenue)}
                icon={DollarSign}
                description="Ingresos del período"
              />
              <StatCard
                title="Reservaciones"
                value={analytics.totalBookings.toLocaleString()}
                icon={TrendingUp}
                description="Reservaciones completadas"
              />
              <StatCard
                title="Establecimientos"
                value={analytics.activeEstablishments.toLocaleString()}
                icon={MapPin}
                description="Establecimientos activos"
              />
            </div>

            {/* Charts Grid */}
            <div className="grid gap-4 md:grid-cols-2">
              {/* Top Destinations */}
              <Card>
                <CardHeader>
                  <CardTitle>Destinos Más Visitados</CardTitle>
                  <CardDescription>
                    Top destinos del período seleccionado
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {analytics.topDestinations.map((destination, index) => (
                      <div key={destination.id} className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-sm font-bold text-primary">
                            {index + 1}
                          </div>
                          <span className="font-medium">{destination.name}</span>
                        </div>
                        <span className="text-muted-foreground">
                          {destination.visits.toLocaleString()} visitas
                        </span>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* Revenue by Category */}
              <Card>
                <CardHeader>
                  <CardTitle>Ingresos por Categoría</CardTitle>
                  <CardDescription>
                    Distribución de ingresos por tipo de servicio
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {analytics.revenueByCategory.map((item) => (
                      <div key={item.category}>
                        <div className="flex items-center justify-between mb-2">
                          <span className="font-medium capitalize">{item.category}</span>
                          <span className="text-muted-foreground">
                            {formatCurrency(item.revenue)}
                          </span>
                        </div>
                        <div className="w-full bg-secondary h-2 rounded-full overflow-hidden">
                          <div
                            className="bg-primary h-full rounded-full transition-all"
                            style={{
                              width: `${(item.revenue / analytics.totalRevenue) * 100}%`,
                            }}
                          />
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* User Growth Chart */}
            <Card>
              <CardHeader>
                <CardTitle>Crecimiento de Usuarios</CardTitle>
                <CardDescription>
                  Evolución de usuarios registrados - Tasa de conversión: {analytics.conversionRate.toFixed(2)}%
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="h-64 flex items-end justify-between gap-2">
                  {analytics.userGrowth.map((point) => (
                    <div key={point.date} className="flex-1 flex flex-col items-center gap-2">
                      <div
                        className="w-full bg-primary rounded-t transition-all hover:bg-primary/80"
                        style={{
                          height: `${(point.users / Math.max(...analytics.userGrowth.map(p => p.users))) * 100}%`,
                          minHeight: '20px',
                        }}
                      />
                      <span className="text-xs text-muted-foreground">
                        {new Date(point.date).toLocaleDateString('es', { day: 'numeric', month: 'short' })}
                      </span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </>
        )}
      </div>
    </DashboardLayout>
  );
};

export default Analytics;
