// export const dynamic = 'force-dynamic';
"use client";

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2 } from "lucide-react";
import { RANGE_OPTIONS, getRangeOption } from "@/lib/chartRangeOptions";
import { CardFooter, } from "@/components/ui/card";
import { CreditCard, DollarSign, ShoppingCart, Users, } from "lucide-react";
import Link from "next/link";
import { RecentOrders } from "@/components/admin/dashboard/recent-orders";
import { RecentReviews } from "@/components/admin/dashboard/recent-reviews";
import { useEffect, useState } from "react";
import PriceDisplay from "@/components/ui/formattedPrice";

interface AdminSummaryProps {
  searchParams: {
    page1?: string;
    page1From?: string;
    page1To?: string;
  };
}


const safePercent = (current: number, previous: number) => {
  if (!previous || !current) return "0.00"

  const result = (current / previous) * 100
  return isNaN(result) || !isFinite(result) ? "0.00" : result.toFixed(2)
}



const AdminSummary = ({ searchParams }: AdminSummaryProps) => {
  const { page1, page1From, page1To } = searchParams;

  // Get date range for filtering data
  const dataRangeOption = getRangeOption(page1, page1From, page1To) || RANGE_OPTIONS.last_7_days;
  const endDate = dataRangeOption.endDate || new Date();
  const [totalRevenue, setTotalRevenue] = useState<number | null>(null)
  const [totalOrdersCount, setTotalOrdersCount] = useState<number | null>(null);
  const [totalCustomersCount, setTotalCustomersCount] = useState<number | null>(null);
  const [totalCouponsCount, setTotalCouponsCount] = useState<number | null>(null);
  const [thisMonthOrdersCount, setThisMonthOrdersCount] = useState<number | null>(null);
  const [thisMonthReviewsCount, setThisMonthReviewsCount] = useState<number | null>(null);
  const [thisMonthRevenue, setThisMonthRevenue] = useState<number | null>(null);
  const [thisMonthCustomersCount, setThisMonthCustomersCount] = useState<number | null>(null);
  const [lastMonthOrdersCount, setLastMonthOrdersCount] = useState<number | null>(null);
  const [lastMonthRevenue, setLastMonthRevenue] = useState<number | null>(null);
  const [lastMonthCustomersCount, setLastMonthCustomersCount] = useState<number | null>(null);

  const [revenueComparison, setRevenueComparison] = useState<string | null>(null);
  const [ordersComparison, setOrdersComparison] = useState<string | null>(null);
  const [customersComparison, setCustomersComparison] = useState<string | null>(null);

  const [latestOrders, setLatestOrders] = useState<any[]>([]);
  const [recentReviews, setRecentReviews] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchDashboardData = async () => {
    try {
      const response = await fetch("/api/admin/dashboard", {
        method: "GET",
      });

      if (!response.ok) {
        throw new Error("Failed to fetch dashboard data");
      }

      const data = await response.json();
      setTotalRevenue(data.totalRevenue?._sum.order_total_amount ?? 0);
      setTotalOrdersCount(data.totalOrdersCount);
      setTotalCustomersCount(data.totalCustomersCount);
      setTotalCouponsCount(data.totalCouponsCount);
      setLatestOrders(data.latestOrders);
      setRecentReviews(data.recentReviews);
      setThisMonthOrdersCount(data.thisMonthOrdersCount);
      setThisMonthReviewsCount(data.thisMonthReviewsCount);
      setThisMonthRevenue(data.thisMonthRevenue?._sum.order_total_amount ?? 0);
      setThisMonthCustomersCount(data.thisMonthCustomersCount);
      setLastMonthOrdersCount(data.lastMonthOrdersCount);
      setLastMonthRevenue(data.lastMonthRevenue?._sum.order_total_amount ?? 0);
      setLastMonthCustomersCount(data.lastMonthCustomersCount);

      setRevenueComparison(
        safePercent(
          data.thisMonthRevenue?._sum.order_total_amount ?? 0,
          data.lastMonthRevenue?._sum.order_total_amount ?? 0
        )
      )

      setOrdersComparison(
        safePercent(
          data.thisMonthOrdersCount ?? 0,
          data.lastMonthOrdersCount ?? 0
        )
      )

      setCustomersComparison(
        safePercent(
          data.thisMonthCustomersCount ?? 0,
          data.lastMonthCustomersCount ?? 0
        )
      )



    } catch (error) {
      console.error("Error fetching dashboard data:", error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchDashboardData()
  }, [])

  if (loading) {
    return <Loader2 className="h-8 w-8 animate-spin text-gray-500" />
  }

  return (


    <div className="space-y-2 py-5">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">Dashboard</h1>
        <p className="text-muted-foreground">
          Overview of your store performance and recent activity.
        </p>
      </div>
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <DashboardCard
          title="Total Revenue (Last 30 days)"
          value={thisMonthRevenue?.toString() ?? "Loading..."}
          description={`${revenueComparison} from last month`}
          icon={<DollarSign className="h-4 w-4 text-muted-foreground" />}
        />
        <DashboardCard
          title="Orders (Last 30 days)"
          value={totalOrdersCount?.toString() ?? "Loading..."}
          description={`${ordersComparison} from last month`}
          icon={<ShoppingCart className="h-4 w-4 text-muted-foreground" />}
        />
        <DashboardCard
          title="Customers (Last 30 days)"
          value={thisMonthCustomersCount?.toString() ?? "Loading..."}
          description={`${customersComparison} from last month`}
          icon={<Users className="h-4 w-4 text-muted-foreground" />}
        />
        <DashboardCard
          title="Active Coupons"
          value={totalCouponsCount?.toString() ?? "Loading..."}
          description=""
          icon={<CreditCard className="h-4 w-4 text-muted-foreground" />}
        />
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
        <Card className="col-span-4">
          <CardHeader>
            <CardTitle>Recent Orders</CardTitle>
            <CardDescription>
              You have received {thisMonthOrdersCount} orders this month.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <RecentOrders orders={latestOrders} />
          </CardContent>
          <CardFooter>
            <Link
              href="/admin/orders"
              className="text-sm text-blue-500 hover:underline"
            >
              View all orders
            </Link>
          </CardFooter>
        </Card>
        <Card className="col-span-3">
          <CardHeader>
            <CardTitle>Recent Reviews</CardTitle>
            <CardDescription>
              You have received {thisMonthReviewsCount} reviews this month.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <RecentReviews reviews={recentReviews} />
          </CardContent>
          <CardFooter>
            <Link
              href="/reviews"
              className="text-sm text-blue-500 hover:underline"
            >
              View all reviews
            </Link>
          </CardFooter>
        </Card>
      </div>
    </div>
  );


};

export default AdminSummary;

interface DashboardCardProps {
  title: string;
  value: string;
  description: string;
  icon: React.ReactNode;
}

function DashboardCard({
  title,
  value,
  description,
  icon,
}: DashboardCardProps) {


  if (title === 'Total Revenue') {
    return (
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">{title}</CardTitle>
          {icon}
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold"><PriceDisplay price={Number(value)} /></div>
          <p className="text-xs text-muted-foreground">{description}</p>
        </CardContent>
      </Card>
    )
  }
  else {
    return (
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-sm font-medium">{title}</CardTitle>
          {icon}
        </CardHeader>
        <CardContent>
          <div className="text-2xl font-bold">{value}</div>
          <p className="text-xs text-muted-foreground">{description}</p>
        </CardContent>
      </Card>
    )
  }
}