"use client";

import Image from "next/image";
import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import type { AppDispatch, RootState } from "@/state/store";
import { fetchProductsTrend } from "@/state/dashboard/dashboardSlice";
import {
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";

const periods = ["Year", "Month", "Week", "Daily"] as const;
type PeriodType = (typeof periods)[number];

const periodToInterval: Record<PeriodType, "yearly" | "monthly" | "weekly" | "daily"> = {
  Year: "yearly",
  Month: "monthly",
  Week: "weekly",
  Daily: "daily",
};

type TooltipPayloadItem = {
  dataKey: string;
  value: number;
};

function ChartTooltip({ active, payload }: { active?: boolean; payload?: TooltipPayloadItem[] }) {
  if (!active || !payload || payload.length === 0) return null;

  const newProducts = payload.find((item) => item.dataKey === "newProducts");
  const usedProducts = payload.find((item) => item.dataKey === "usedProducts");

  return (
    <div className="rounded-xl border border-[#E4E7EC] bg-white px-3.5 py-2.5 shadow-[0_12px_28px_rgba(15,23,42,0.14)]">
      {newProducts && (
        <div className="flex items-center gap-2">
          <Image src="/assets/newproducts.png" alt="" width={16} height={16} />
          <div>
            <p className="text-[14px] font-bold leading-none text-[#1657D9]">
              {newProducts.value.toLocaleString()}
            </p>
            <p className="mt-0.5 text-[11px] text-[#667085]">New Products</p>
          </div>
        </div>
      )}
      {usedProducts && (
        <div className="mt-2 flex items-center gap-2 border-t border-[#F2F4F7] pt-2">
          <Image src="/assets/newproducts.png" alt="" width={16} height={16} />
          <div>
            <p className="text-[14px] font-bold leading-none text-[#F59E0B]">
              {usedProducts.value.toLocaleString()}
            </p>
            <p className="mt-0.5 text-[11px] text-[#667085]">Used Products</p>
          </div>
        </div>
      )}
    </div>
  );
}

export default function ProductsOverviewChart() {
  const dispatch = useDispatch<AppDispatch>();
  const [period, setPeriod] = useState<PeriodType>("Year");
  const { trend, loading } = useSelector((state: RootState) => state.dashboard);

  useEffect(() => {
    const now = new Date();
    const interval = periodToInterval[period];
    dispatch(
      fetchProductsTrend({
        interval,
        year: now.getFullYear(),
        month: interval === "monthly" ? now.getMonth() + 1 : undefined,
      })
    );
  }, [dispatch, period]);

  const chartData = useMemo(() => {
    if (!trend?.data || trend.data.length === 0) {
      return [];
    }
    return trend.data.map((item) => ({
      name: item.label,
      newProducts: item.newProducts || 0,
      usedProducts: item.usedProducts || 0,
    }));
  }, [trend]);

  return (
    <div className="flex h-[400px] min-w-0 flex-col rounded-xl border border-[#E4E7EC] bg-white p-5">
      <div className="mb-4 flex flex-shrink-0 flex-wrap items-center justify-between gap-3">
        <div>
          <h2 className="text-[16px] font-semibold text-[#101828]">Products Overview</h2>
          <div className="mt-2 flex items-center gap-4 text-[12px] font-medium">
            <span className="flex items-center gap-1.5 text-[#1657D9]">
              <span className="h-2.5 w-2.5 rounded-full bg-[#1657D9]" />
              New Products
            </span>
            <span className="flex items-center gap-1.5 text-[#F59E0B]">
              <span className="h-2.5 w-2.5 rounded-full bg-[#F59E0B]" />
              Used Products
            </span>
          </div>
        </div>

        <div className="flex gap-1 rounded-lg bg-[#F2F4F7] p-1 text-[12px]">
          {periods.map((item) => (
            <button
              key={item}
              type="button"
              onClick={() => setPeriod(item)}
              className={`rounded-md px-3 py-1.5 transition-colors ${
                period === item ? "bg-white font-medium text-[#101828] shadow-sm" : "text-[#667085]"
              }`}
            >
              {item}
            </button>
          ))}
        </div>
      </div>

      <div className="relative min-h-0 flex-1">
        {loading.trend && (
          <div className="absolute inset-0 z-10 flex items-center justify-center bg-white/60">
            <div className="h-6 w-6 animate-spin rounded-full border-2 border-[#1657D9] border-t-transparent" />
          </div>
        )}
        {chartData.length === 0 && !loading.trend ? (
          <div className="flex h-full items-center justify-center text-[13px] text-[#667085]">
            No product trend data found for this period.
          </div>
        ) : (
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={chartData} margin={{ top: 10, right: 10, left: -10, bottom: 0 }}>
              <CartesianGrid stroke="#F0F2F5" strokeDasharray="3 3" vertical={false} />
              <XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: "#98A2B3" }} />
              <YAxis axisLine={false} tickLine={false} tick={{ fontSize: 11, fill: "#98A2B3" }} />
              <Tooltip
                content={<ChartTooltip />}
                cursor={{ stroke: "#CBD5E1", strokeDasharray: "4 4", strokeWidth: 1 }}
              />
              <Line
                type="monotone"
                dataKey="newProducts"
                stroke="#1657D9"
                strokeWidth={2.5}
                dot={false}
                isAnimationActive={false}
                activeDot={{ r: 5, fill: "#1657D9", stroke: "#fff", strokeWidth: 2 }}
              />
              <Line
                type="monotone"
                dataKey="usedProducts"
                stroke="#F59E0B"
                strokeWidth={2.5}
                dot={false}
                isAnimationActive={false}
                activeDot={{ r: 5, fill: "#F59E0B", stroke: "#fff", strokeWidth: 2 }}
              />
            </LineChart>
          </ResponsiveContainer>
        )}
      </div>
    </div>
  );
}
