import React, { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ChannelManagerStats } from '@/hooks/useChannelManager';
import { TrendingUp, TrendingDown, DollarSign, Calendar, Users, Activity } from 'lucide-react';

interface AnalyticsTabProps {
  stats: ChannelManagerStats | null;
  onDateRangeChange: (range: { startDate: string; endDate: string }) => void;
}

export const AnalyticsTab: React.FC<AnalyticsTabProps> = ({ stats, onDateRangeChange }) => {
  const [dateRange, setDateRange] = useState('30');

  const handleDateRangeChange = (value: string) => {
    setDateRange(value);
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - parseInt(value));
    
    onDateRangeChange({
      startDate: startDate.toISOString().split('T')[0],
      endDate: endDate.toISOString().split('T')[0],
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold">Analytics y Reportes</h2>
          <p className="text-muted-foreground">Análisis detallado de rendimiento y métricas clave</p>
        </div>
        <Select value={dateRange} onValueChange={handleDateRangeChange}>
          <SelectTrigger className="w-48">
            <SelectValue placeholder="Rango de fechas" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="7">Últimos 7 días</SelectItem>
            <SelectItem value="30">Últimos 30 días</SelectItem>
            <SelectItem value="90">Últimos 90 días</SelectItem>
            <SelectItem value="365">Último año</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Key Performance Indicators */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Ingresos Totales</p>
                <p className="text-3xl font-bold">${stats?.totalRevenue.toLocaleString() || '0'}</p>
                <div className="flex items-center mt-2 text-sm text-green-600">
                  <TrendingUp className="w-4 h-4 mr-1" />
                  <span>+12.5%</span>
                </div>
              </div>
              <DollarSign className="h-10 w-10 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Reservas Totales</p>
                <p className="text-3xl font-bold">{stats?.totalBookings || 0}</p>
                <div className="flex items-center mt-2 text-sm text-green-600">
                  <TrendingUp className="w-4 h-4 mr-1" />
                  <span>+8.2%</span>
                </div>
              </div>
              <Calendar className="h-10 w-10 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Tasa de Ocupación</p>
                <p className="text-3xl font-bold">{stats?.occupancyRate || 0}%</p>
                <div className="flex items-center mt-2 text-sm text-red-600">
                  <TrendingDown className="w-4 h-4 mr-1" />
                  <span>-2.4%</span>
                </div>
              </div>
              <Activity className="h-10 w-10 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Tarifa Promedio</p>
                <p className="text-3xl font-bold">${stats?.averageRate.toFixed(2) || '0'}</p>
                <div className="flex items-center mt-2 text-sm text-green-600">
                  <TrendingUp className="w-4 h-4 mr-1" />
                  <span>+5.8%</span>
                </div>
              </div>
              <Users className="h-10 w-10 text-muted-foreground" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Channel Performance Detailed */}
      <Card>
        <CardHeader>
          <CardTitle>Rendimiento Detallado por Canal</CardTitle>
          <CardDescription>Análisis comparativo de todos los canales de distribución</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-3 px-4">Canal</th>
                  <th className="text-right py-3 px-4">Reservas</th>
                  <th className="text-right py-3 px-4">Ingresos</th>
                  <th className="text-right py-3 px-4">Ingreso Promedio</th>
                  <th className="text-right py-3 px-4">% del Total</th>
                </tr>
              </thead>
              <tbody>
                {stats?.channelPerformance.map((channel, index) => {
                  const avgRevenue = channel.bookings > 0 ? channel.revenue / channel.bookings : 0;
                  const percentage = stats.totalRevenue > 0 ? (channel.revenue / stats.totalRevenue) * 100 : 0;
                  
                  return (
                    <tr key={index} className="border-b hover:bg-muted/50">
                      <td className="py-3 px-4 font-medium">{channel.channelName}</td>
                      <td className="text-right py-3 px-4">{channel.bookings}</td>
                      <td className="text-right py-3 px-4">${channel.revenue.toLocaleString()}</td>
                      <td className="text-right py-3 px-4">${avgRevenue.toFixed(2)}</td>
                      <td className="text-right py-3 px-4">{percentage.toFixed(1)}%</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* Revenue Insights */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle>Insights de Ingresos</CardTitle>
            <CardDescription>Análisis y recomendaciones basadas en datos</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="p-4 border rounded-lg">
              <div className="flex items-start space-x-3">
                <TrendingUp className="w-5 h-5 text-green-600 mt-0.5" />
                <div>
                  <p className="font-medium">Mejor Canal de Performance</p>
                  <p className="text-sm text-muted-foreground mt-1">
                    {stats?.channelPerformance[0]?.channelName || 'N/A'} generó el mayor ingreso este período
                  </p>
                </div>
              </div>
            </div>

            <div className="p-4 border rounded-lg">
              <div className="flex items-start space-x-3">
                <Activity className="w-5 h-5 text-blue-600 mt-0.5" />
                <div>
                  <p className="font-medium">Oportunidad de Optimización</p>
                  <p className="text-sm text-muted-foreground mt-1">
                    Considera ajustar precios en días de baja ocupación para maximizar ingresos
                  </p>
                </div>
              </div>
            </div>

            <div className="p-4 border rounded-lg">
              <div className="flex items-start space-x-3">
                <DollarSign className="w-5 h-5 text-yellow-600 mt-0.5" />
                <div>
                  <p className="font-medium">Revenue Management</p>
                  <p className="text-sm text-muted-foreground mt-1">
                    La tarifa promedio ha aumentado {((stats?.averageRate || 0) * 0.058).toFixed(2)}% vs. período anterior
                  </p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Métricas de Distribución</CardTitle>
            <CardDescription>Balance entre canales directos y OTAs</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-3">
              {stats?.channelPerformance.map((channel, index) => {
                const percentage = stats.totalRevenue > 0 ? (channel.revenue / stats.totalRevenue) * 100 : 0;
                
                return (
                  <div key={index} className="space-y-2">
                    <div className="flex justify-between text-sm">
                      <span className="font-medium">{channel.channelName}</span>
                      <span className="text-muted-foreground">{percentage.toFixed(1)}%</span>
                    </div>
                    <div className="w-full bg-muted rounded-full h-2">
                      <div 
                        className="bg-primary rounded-full h-2 transition-all" 
                        style={{ width: `${percentage}%` }}
                      />
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
};
