"use client";
import { useEffect, useState } from "react";
import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  ReferenceLine,
} from "recharts";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/src/components/reusables/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import Cards from "../cards";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/src/redux/store";
import { useGetStats } from "@/src/utils/hooks/useGetAdmindashboardStats";
import { setAdminStats } from "@/src/redux/appActions";
import { RotateCcw } from "lucide-react";
import {
  useGetMonthlyGraphData,
  useGetYearlyGraphData,
} from "@/src/utils/hooks/useGetAdmindashboardStats";

type MonthlySalesComparison = {
  previous_year: number;
  current_year: number;
};

type TransformedData = {
  name: string;
  value2024: number;
  value2025: number;
  highlight: boolean;
};

export default function DashboardPage() {
  const monthNames = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
  ];

  const statsData = useSelector(
    (state: RootState) => state.counter.adminSettings.stats
  );

  const dispatch = useDispatch();

  // Function to get month label
  const getMonthLabel = (monthIndex: number) => {
    return monthNames[monthIndex - 1];
  };

  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1;

  const [selectedYear, setSelectedYear] = useState<string>(
    currentYear.toString()
  );

  const [selectedYear1, setSelectedYear1] = useState<string>(
    currentYear.toString()
  );

  const years = () => {
    const currentYear =
      (yearlyData?.payload?.year || new Date().getFullYear()) - 1;
    return Array.from({ length: 10 }, (_, i) => currentYear - i);
  };

  const years1 = () => {
    const currentYear =
      (monthlyData?.payload?.year || new Date().getFullYear()) - 1;
    return Array.from({ length: 10 }, (_, i) => currentYear - i);
  };

  const { data: statsValues } = useGetStats();

  useEffect(() => {
    if (statsValues && statsValues?.payload) {
      dispatch(setAdminStats(statsValues.payload));
    }
  }, [statsValues, dispatch]);

  const {
    data: monthlyData,
    selectedMonth,
    setSelectedMonth,
    refetch: monthlyStatRefetch,
  } = useGetMonthlyGraphData(selectedYear1);

  const dailySales = monthlyData?.payload?.daily_sales ?? {};
  console.log(dailySales, "is daily sales");
  // Transform daily data for chart
  const transformedDailyData = monthlyData?.payload?.daily_sales
    ? Object.entries(dailySales).map(([day, value]) => ({
        day: day,
        value: Number(value),
        highlight: Number(day) === 16, // Highlights day 16
      }))
    : Array.from({ length: 31 }, (_, i) => ({
        day: String(i + 1),
        value: 0,
        highlight: i + 1 === 16,
      }));

  // reference line value
  const highestDailyValue = Math.max(
    ...transformedDailyData.map((item) => item.value),
    0
  );

  const { data: yearlyData, refetch: yearlyStatRefetch } =
    useGetYearlyGraphData(selectedYear);

  const rawMonthlyData = yearlyData?.payload?.monthly_sales_comparison as
    | Record<string, MonthlySalesComparison>
    | undefined;

  const transformedYearlyData: TransformedData[] = rawMonthlyData
    ? Object.entries(rawMonthlyData).map(([month, values]) => ({
        name: month.substring(0, 3),
        value2024: Number(values.previous_year),
        value2025: Number(values.current_year),
        highlight: month === "May",
      }))
    : [];

  console.log(transformedYearlyData, "is yearly");

  const valueKeys = transformedYearlyData.length
    ? Object.keys(transformedYearlyData[0]!).filter((key) =>
        key.startsWith("value")
      )
    : [];

  // Find the highest value across all years
  const highestMonthlyValue = Math.max(
    ...transformedYearlyData.flatMap((item) =>
      valueKeys.map((key) => item[key as keyof typeof item] as number)
    ),
    0
  );

  // Find the month with the highest value
  const highestMonthEntry = transformedYearlyData.find((item) =>
    valueKeys.some(
      (key) => item[key as keyof typeof item] === highestMonthlyValue
    )
  );
  const highestMonth = highestMonthEntry?.name || "May";

  const [salutation, setSalutation] = useState<string>("");

  const hour = new Date().getHours();

  useEffect(() => {
    if (hour >= 5 && hour < 12) {
      setSalutation("Good morning,");
    } else if (hour >= 12 && hour < 17) {
      setSalutation("Good afternoon,");
    } else {
      setSalutation("Good evening,");
    }
  }, [hour]);

  useEffect(() => {
    if (selectedYear) yearlyStatRefetch();
  }, [selectedYear]);

  useEffect(() => {
    if (selectedYear1 || selectedMonth) monthlyStatRefetch();
  }, [selectedYear1, selectedMonth]);

  return (
    <div className="space-y-6">
      {/* Greeting */}
      <h1 className="text-2xl font-semibold text-[#16166C]">
        {salutation} Super admin! 👋
      </h1>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Cards
          title="Profit Sales"
          statValue={statsData.total_sales}
          profitValue={23}
          currency="NGN"
          iconPath="/images/naira.svg"
        />
        <Cards
          title="Total Customers"
          statValue={statsData.total_users_count}
          profitValue={6}
          iconPath="/images/hand.svg"
        />
        <Cards
          title="New Customers"
          statValue={statsData.new_users_count}
          profitValue={3}
          iconPath="/images/person.svg"
        />
        <Cards
          title="Deleted Accounts"
          statValue={statsData.deleted_accounts_count}
          profitValue={3}
          iconPath="/images/modules.svg"
        />
      </div>

      {/* Total Revenue Chart */}
      <Card className="overflow-hidden relative">
        <CardHeader className="flex flex-col items-center justify-between pb-2 md:h-auto h-[50px]">
          <CardTitle className="font-bold text-[#464255] text-[14px] md:static absolute left-5 top-3.5">
            Total Revenue
          </CardTitle>
          <div className="flex justify-end items-center md:w-full gap-4 -mt-6 mb-8 md:static absolute right-5 top-10">
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 rounded-full bg-blue-500"></div>
              <span className="text-sm text-gray-500">
                {yearlyData?.payload?.previous_year || currentYear - 1}
              </span>
            </div>
            <div className="flex items-center gap-1">
              <div className="w-3 h-3 rounded-full bg-red-500"></div>
              <span className="text-sm text-gray-500">
                {yearlyData?.payload?.year || currentYear}
              </span>
            </div>
          </div>
        </CardHeader>
        <div className="w-full flex items-center justify-end -mx-4">
          <Select
            value={selectedYear}
            onValueChange={(value) =>
              setSelectedYear(value || String(currentYear))
            }
          >
            <SelectTrigger className="w-[120px]">
              <SelectValue placeholder="Select year">
                {selectedYear || "Select year"}
              </SelectValue>
            </SelectTrigger>
            <SelectContent>
              {years().map((year) => (
                <SelectItem key={year} value={String(year)}>
                  {year}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {selectedYear !== String(currentYear) && (
            <button
              onClick={() => setSelectedYear(String(currentYear))}
              className="text-gray-500 hover:text-gray-900 p-2 rounded transition-colors"
              title="Reset to current year"
            >
              <RotateCcw size={18} />
            </button>
          )}
        </div>
        <CardContent className="p-0">
          <div className="h-[300px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart
                data={transformedYearlyData}
                margin={{ top: 20, right: 30, left: 30, bottom: 30 }}
              >
                <defs>
                  <linearGradient id="colorBlue" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.1} />
                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                  </linearGradient>
                  <linearGradient id="colorRed" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#ef4444" stopOpacity={0.1} />
                    <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid
                  strokeDasharray="3 3"
                  vertical={false}
                  horizontal={false}
                />
                <XAxis
                  dataKey="name"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 12 }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => {
                    if (value === 0) return "0";
                    if (value >= 1000000) return `${value / 1000000}M`;
                    return `${value / 1000}K`;
                  }}
                />
                <Tooltip
                  formatter={(value: number) => [
                    `₦ ${value.toLocaleString()}`,
                    "",
                  ]}
                />
                <ReferenceLine
                  x={highestMonth}
                  stroke="#2D9CDB"
                  strokeDasharray="3 3"
                  label={{
                    value: `₦ ${highestMonthlyValue.toLocaleString()}`,
                    position: "top",
                    fill: "#2D9CDB",
                    fontSize: 12,
                    offset: 10,
                    content: (props) => {
                      const viewBox = props.viewBox as {
                        x?: number;
                        y?: number;
                      };

                      return (
                        <g>
                          <rect
                            x={viewBox.x ? viewBox.x - 50 : 0}
                            y={viewBox.y ? viewBox.y - 15 : 0}
                            width={100}
                            height={20}
                            rx={4}
                            fill="#E3F2FD"
                          />
                          <text
                            x={viewBox.x || 0}
                            y={viewBox.y || 0}
                            fill="#2D9CDB"
                            fontSize={12}
                            textAnchor="middle"
                          >
                            {props.value}
                          </text>
                        </g>
                      );
                    },
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="value2024"
                  stroke="#3b82f6"
                  strokeWidth={2}
                  fillOpacity={1}
                  fill="url(#colorBlue)"
                  dot={(props) => {
                    const { cx, cy, payload } = props;
                    return payload.highlight ? (
                      <circle
                        cx={cx}
                        cy={cy}
                        r={4}
                        fill="#3b82f6"
                        stroke="#fff"
                        strokeWidth={2}
                      />
                    ) : (
                      <circle cx={cx} cy={cy} r={0} fill="transparent" />
                    );
                  }}
                />
                <Area
                  type="monotone"
                  dataKey="value2025"
                  stroke="#ef4444"
                  strokeWidth={2}
                  fillOpacity={1}
                  fill="url(#colorRed)"
                  dot={(props) => {
                    const { cx, cy, payload } = props;
                    return payload.highlight ? (
                      <circle
                        cx={cx}
                        cy={cy}
                        r={4}
                        fill="#ef4444"
                        stroke="#fff"
                        strokeWidth={2}
                      />
                    ) : (
                      <circle cx={cx} cy={cy} r={0} fill="transparent" />
                    );
                  }}
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Revenue Tracking Chart */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-[#464255] text-[14px] font-bold">
            Revenue Tracking
          </CardTitle>
          <div className="flex md:flex-row flex-col items-center justify-end -mx-4 md:gap-x-4 md:gap-y-0 gap-y-4">
            <Select
              // defaultValue={selectedYear}
              value={selectedYear1}
              onValueChange={(value) =>
                setSelectedYear1(value || String(currentYear))
              }
            >
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="Select year">
                  {selectedYear1 || "Select year"}
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {years1().map((year) => (
                  <SelectItem key={year} value={String(year)}>
                    {year}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select
              value={String(selectedMonth)}
              onValueChange={(value) => {
                setSelectedMonth(parseInt(value));
              }}
            >
              <SelectTrigger className="w-[120px]">
                <SelectValue placeholder="Select month">
                  {selectedMonth === currentMonth
                    ? monthNames[currentMonth - 1]
                    : monthNames[selectedMonth - 1]}
                </SelectValue>
              </SelectTrigger>
              <SelectContent>
                {monthNames.map((month, index) => (
                  <SelectItem key={index} value={String(index + 1)}>
                    {month}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            {(selectedYear1 !== String(currentYear) ||
              selectedMonth !== currentMonth) && (
              <button
                onClick={() => {
                  setSelectedYear1(String(currentYear));
                  setSelectedMonth(currentMonth);
                }}
                className="md:text-[#464255] text-gray-800 hover:text-gray-900 p-2 flex gap-x-4 items-center justify-center rounded md:transition-colors md:bg-transparent bg-red-500 md:w-auto w-full"
                title="Reset"
              >
                <span className="md:hidden inline">clear</span>
                <RotateCcw size={18} />
              </button>
            )}
          </div>
        </CardHeader>
        <CardContent className="p-0">
          <div className="h-[250px] w-full">
            <ResponsiveContainer width="100%" height="100%">
              <AreaChart
                data={transformedDailyData}
                margin={{ top: 20, right: 30, left: 30, bottom: 30 }}
              >
                <defs>
                  <linearGradient id="colorPurple" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="40%" stopColor="#3D37F1" stopOpacity={0.1} />
                    <stop offset="95%" stopColor="#3D37F1" stopOpacity={0} />
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis
                  dataKey="day"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 12 }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 12 }}
                  tickFormatter={(value) => `${value / 1000}K`}
                />
                <Tooltip
                  formatter={(value: number) => `₦ ${value.toLocaleString()}`}
                  labelFormatter={(label) =>
                    `Day ${label}, ${getMonthLabel(selectedMonth)}`
                  }
                />
                <ReferenceLine
                  x="16"
                  stroke="#ef4444"
                  strokeDasharray="3 3"
                  label={{
                    value:
                      highestDailyValue > 0
                        ? highestDailyValue.toLocaleString()
                        : "0",
                    position: "top",
                    fill: "#ef4444",
                    fontSize: 12,
                    offset: 10,
                  }}
                />
                <Area
                  type="linear"
                  dataKey="value"
                  stroke="#1A2B88"
                  strokeWidth={2}
                  fill="url(#colorPurple)"
                  fillOpacity={1}
                  activeDot={{ r: 8 }}
                  dot={false}
                />
              </AreaChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
