"use client"

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { clientFetch } from "@/lib/api";
import { useToast } from "@/hooks/use-toast";
import { Skeleton } from "@/components/ui/skeleton";
import { TrendingUp, DollarSign } from "lucide-react";

interface RevenueData {
  _id: {
    year: number;
    month: number;
    day: number;
  };
  revenue: number;
  orders: number;
}

interface RevenueChartProps {
  timeRange: string;
}

export default function RevenueChart({ timeRange }: RevenueChartProps) {
  const [data, setData] = useState<RevenueData[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { toast } = useToast();

  useEffect(() => {
    const fetchRevenueData = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const response = await clientFetch<RevenueData[]>(`/analytics/revenue-trends?period=${timeRange}`);
        setData(response);
      } catch (err) {
        console.error('Error fetching revenue data:', err);
        setError('Failed to load revenue data');
        toast({
          title: "Error",
          description: "Failed to load revenue trends data.",
          variant: "destructive",
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchRevenueData();
  }, [timeRange, toast]);

  const totalRevenue = data.reduce((sum, item) => sum + item.revenue, 0);
  const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
  const averageRevenue = data.length > 0 ? totalRevenue / data.length : 0;

  const formatDate = (item: RevenueData) => {
    const date = new Date(item._id.year, item._id.month - 1, item._id.day);
    return date.toLocaleDateString('en-US', { 
      month: 'short', 
      day: 'numeric' 
    });
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Revenue Trends
          </CardTitle>
          <CardDescription>
            Revenue performance over the selected time period
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            <Skeleton className="h-64 w-full" />
            <div className="grid grid-cols-3 gap-4">
              <Skeleton className="h-16" />
              <Skeleton className="h-16" />
              <Skeleton className="h-16" />
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Revenue Trends
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <DollarSign className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">Failed to load revenue data</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (data.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5" />
            Revenue Trends
          </CardTitle>
          <CardDescription>
            Revenue performance over the selected time period
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8">
            <DollarSign className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
            <p className="text-muted-foreground">No revenue data available for this period</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <TrendingUp className="h-5 w-5" />
          Revenue Trends
        </CardTitle>
        <CardDescription>
          Revenue performance over the selected time period
        </CardDescription>
      </CardHeader>
      <CardContent>
        {/* Simple bar chart representation */}
        <div className="space-y-4">
          <div className="h-64 flex items-end justify-between gap-1">
            {data.map((item, index) => {
              const maxRevenue = Math.max(...data.map(d => d.revenue));
              const height = maxRevenue > 0 ? (item.revenue / maxRevenue) * 100 : 0;
              
              return (
                <div key={index} className="flex-1 flex flex-col items-center">
                  <div 
                    className="w-full bg-primary/20 hover:bg-primary/30 transition-colors rounded-t"
                    style={{ height: `${height}%` }}
                    title={`${formatDate(item)}: $${item.revenue.toFixed(2)}`}
                  />
                  <div className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
                    {formatDate(item)}
                  </div>
                </div>
              );
            })}
          </div>
          
          {/* Summary stats */}
          <div className="grid grid-cols-3 gap-4 pt-4 border-t">
            <div className="text-center">
              <div className="text-2xl font-bold text-green-600">
                ${totalRevenue.toFixed(2)}
              </div>
              <div className="text-sm text-muted-foreground">Total Revenue</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-blue-600">
                {totalOrders}
              </div>
              <div className="text-sm text-muted-foreground">Total Orders</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-bold text-purple-600">
                ${averageRevenue.toFixed(2)}
              </div>
              <div className="text-sm text-muted-foreground">Avg Daily Revenue</div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
} 