"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Rectangle,
} from "recharts";
import {
  ArrowDownIcon,
  ArrowUpIcon,
  DollarSignIcon,
  PackageIcon,
} from "lucide-react";
import {
  Analytics,
  AnalyticsResponse,
  useListAllAnalyticsQuery,
} from "@/redux/services/branchs.api";
import Image from "next/image";

const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042"];

export default function Dashboard() {
  const { data: analyticsData } = useListAllAnalyticsQuery();
  const [selectedBranch, setSelectedBranch] = useState<string>("home");

  const data = analyticsData && analyticsData[selectedBranch];

  const branches = analyticsData ? Object.keys(analyticsData) : [];

  const barChartData = data
    ? [
        // {
        //   name: "Total",
        //   orders: data.todays.orders,
        //   completed: data.todays.completed,
        // },
        {
          name: "Today's",
          orders: data.todays.orders,
          completed: data.todays.completed,
        },
      ]
    : [];

  const pieChartData = data
    ? [
        { name: "Pending", value: data.total.pending },
        { name: "Completed", value: data.total.completed },
        { name: "Cancelled", value: data.total.cancelled },
      ]
    : [];

  return (
    <div className="container mx-auto p-4">
      <Select onValueChange={setSelectedBranch} defaultValue="home">
        <SelectTrigger className="w-[180px] mb-4">
          <SelectValue placeholder="Select Branch" />
        </SelectTrigger>
        <SelectContent>
          {branches.map((branch) => (
            <SelectItem key={branch} value={branch}>
              {branch.charAt(0).toUpperCase() + branch.slice(1)}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      <h1 className="text-2xl font-semibold leading-none tracking-tight p-2">
        Today{"'"}s Statistics
      </h1>
      {/* <Image
        height={200}
        width={200}
        src="https://api.ibfoods.online/public/Screenshot-2024-09-20-103750-1731082577779.png"
      /> */}
      <div className="border rounded-sm p-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {data && (
          <>
            <StatCard
              title="Orders"
              value={data.todays.orders}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Pending Orders"
              value={data.todays.pending}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Cancelled Orders"
              value={data.todays.cancelled}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Completed Orders"
              value={data.todays.completed}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            {/* <StatCard
              title="Revenue"
              value={`$${data.todays.revenue}`}
              icon={
                <DollarSignIcon className="h-4 w-4 text-muted-foreground" />
              }
            /> */}
          </>
        )}
      </div>

      <h1 className="text-2xl font-semibold leading-none tracking-tight p-2">
        Total Statistics
      </h1>
      <div className="border rounded-sm p-2 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {data && (
          <>
            <StatCard
              title="Total Orders"
              value={data.total.orders}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Pending Orders"
              value={data.total.pending}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Cancelled Orders"
              value={data.total.cancelled}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            <StatCard
              title="Completed Orders"
              value={data.total.completed}
              icon={<PackageIcon className="h-4 w-4 text-muted-foreground" />}
            />
            {/* <StatCard
              title="Revenue"
              value={`$${data.total.revenue}`}
              icon={
                <DollarSignIcon className="h-4 w-4 text-muted-foreground" />
              }
            /> */}
          </>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <Card>
          <CardHeader>
            <CardTitle>Today{"'"}s PickUp Orders</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart
                width={500}
                height={300}
                data={barChartData}
                margin={{
                  top: 5,
                  right: 30,
                  left: 20,
                  bottom: 5,
                }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="name" />
                <YAxis />
                <Tooltip />
                <Legend />
                <Bar
                  dataKey="orders"
                  name="Total Orders"
                  fill="#8884d8"
                  // activeBar={<Rectangle fill="pink" stroke="blue" />}
                />
                <Bar
                  dataKey="completed"
                  name="Completed Orders"
                  fill="#82ca9d"
                  // activeBar={<Rectangle fill="gold" stroke="purple" />}
                />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Total Order Status Distribution</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={pieChartData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label={({ name, percent }) =>
                    `${name} ${(percent * 100).toFixed(0)}%`
                  }
                >
                  {pieChartData.map((entry, index) => (
                    <Cell
                      key={`cell-${index}`}
                      fill={COLORS[index % COLORS.length]}
                    />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

interface StatCardProps {
  title: string;
  value: string | number;
  icon: React.ReactNode;
}

function StatCard({ title, value, icon }: StatCardProps) {
  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>
      </CardContent>
    </Card>
  );
}
