"use client";
import { useState } from "react";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  CartesianGrid,
} from "recharts";

export interface YearlyComparison {
  labels: string[];
  current_year: number[];
  previous_year: number[];
}

const CustomTooltip = ({ active, payload, label }: any) => {
  if (!active || !payload?.length) return null;
  return (
    <div className="bg-[#2A2D36] border border-white/10 rounded-xl px-4 py-3 shadow-xl text-right">
      <p className="text-gray-400 text-xs mb-2">{label}</p>
      {payload.map((p: any) => (
        <p key={p.name} className="text-sm font-bold" style={{ color: p.color }}>
          {p.value.toLocaleString()} ريال —{" "}
          {p.name === "current" ? "هذا العام" : "العام الماضي"}
        </p>
      ))}
    </div>
  );
};

export default function MonthlyCompareChart({
  data,
}: Readonly<{
  data: YearlyComparison;
}>) {
  const [type, setType] = useState<"area" | "bar">("area");

  // Shape the recharts-friendly array from the three parallel arrays.
  const chartData = data.labels.map((month, i) => ({
    month,
    current: data.current_year[i] ?? 0,
    prev: data.previous_year[i] ?? 0,
  }));

  return (
    <div className="bg-[#1E2128] rounded-2xl p-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          {(["area", "bar"] as const).map((t) => (
            <button
              key={t}
              onClick={() => setType(t)}
              className={`px-3 py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all ${type === t ? "bg-[#FCD704] text-[#13151A]" : "bg-[#13151A] text-gray-400"}`}
            >
              {t === "area" ? "مساحي" : "أعمدة"}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <span className="text-gray-400 text-xs">العام الماضي</span>
            <span className="w-3 h-0.5 bg-white/30 inline-block rounded" />
          </div>
          <div className="flex items-center gap-2">
            <span className="text-white text-xs font-semibold">هذا العام</span>
            <span className="w-3 h-0.5 bg-[#FCD704] inline-block rounded" />
          </div>
          <h3 className="text-white font-bold text-base">مقارنة الأرباح السنوية</h3>
        </div>
      </div>
      <ResponsiveContainer width="100%" height={260}>
        {type === "area" ? (
          <AreaChart data={chartData}>
            <defs>
              <linearGradient id="cg" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#FCD704" stopOpacity={0.3} />
                <stop offset="95%" stopColor="#FCD704" stopOpacity={0} />
              </linearGradient>
              <linearGradient id="pg" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#6B7280" stopOpacity={0.2} />
                <stop offset="95%" stopColor="#6B7280" stopOpacity={0} />
              </linearGradient>
            </defs>
            <CartesianGrid
              strokeDasharray="3 3"
              stroke="rgba(255,255,255,0.04)"
              vertical={false}
            />
            <XAxis
              dataKey="month"
              tick={{ fill: "#6B7280", fontSize: 11 }}
              axisLine={false}
              tickLine={false}
            />
            <YAxis
              tick={{ fill: "#6B7280", fontSize: 11 }}
              axisLine={false}
              tickLine={false}
            />
            <Tooltip content={<CustomTooltip />} />
            <Area
              type="monotone"
              dataKey="prev"
              stroke="#4B5563"
              strokeWidth={2}
              fill="url(#pg)"
              dot={false}
            />
            <Area
              type="monotone"
              dataKey="current"
              stroke="#FCD704"
              strokeWidth={2.5}
              fill="url(#cg)"
              dot={false}
            />
          </AreaChart>
        ) : (
          <BarChart data={chartData} barCategoryGap="30%">
            <CartesianGrid
              strokeDasharray="3 3"
              stroke="rgba(255,255,255,0.04)"
              vertical={false}
            />
            <XAxis
              dataKey="month"
              tick={{ fill: "#6B7280", fontSize: 11 }}
              axisLine={false}
              tickLine={false}
            />
            <YAxis
              tick={{ fill: "#6B7280", fontSize: 11 }}
              axisLine={false}
              tickLine={false}
            />
            <Tooltip
              content={<CustomTooltip />}
              cursor={{ fill: "rgba(255,255,255,0.03)" }}
            />
            <Bar dataKey="prev" fill="rgba(107,114,128,0.4)" radius={[4, 4, 0, 0]} />
            <Bar dataKey="current" fill="#FCD704" radius={[4, 4, 0, 0]} />
          </BarChart>
        )}
      </ResponsiveContainer>
    </div>
  );
}
