"use client";

import { useState, useMemo } from "react";
import { useTranslations } from "next-intl";
import { usePractitionerDashboardControllerGetClientsChartV1 } from "@/api/user/practitioner-dashboard/practitioner-dashboard";

export default function PatientsChart() {
  const t = useTranslations("practitioner");
  const [period, setPeriod] = useState<"daily" | "weekly" | "monthly">("weekly");
  const [hoveredBar, setHoveredBar] = useState<number | null>(null);

  // Fetch chart data from API
  const { data: response, isLoading } = usePractitionerDashboardControllerGetClientsChartV1(
    { period, year: new Date().getFullYear() }
  );

  const chartData = (response as any)?.data?.chart_data || [];

  // Calculate max value dynamically or use default
  const maxValue = useMemo(() => {
    if (chartData.length === 0) return 1000;
    const max = Math.max(...chartData.map((d: any) => d.value));
    return Math.ceil(max / 200) * 200 || 1000; // Round up to nearest 200
  }, [chartData]);

  const chartWidth = 500;
  const chartHeight = 250;
  const padding = { top: 20, right: 20, bottom: 30, left: 40 };
  const innerWidth = chartWidth - padding.left - padding.right;
  const innerHeight = chartHeight - padding.top - padding.bottom;

  const barWidth = 16;
  const barSpacing = chartData.length > 0 ? innerWidth / chartData.length : innerWidth / 7;
  const xScale = (index: number) => padding.left + (barSpacing / 2) - (barWidth / 2) + index * barSpacing;
  const yScale = (value: number) => {
    const safeMaxValue = Math.max(maxValue, 1);
    const scaledValue = Math.max(0, Math.min(value / safeMaxValue, 1)) * innerHeight;
    return innerHeight - scaledValue;
  };

  // Generate Y-axis ticks
  const yAxisTicks = useMemo(() => {
    const ticks = [];
    for (let i = 0; i <= maxValue; i += 200) {
      ticks.push(i);
    }
    return ticks;
  }, [maxValue]);

  const handlePeriodChange = (newPeriod: string) => {
    setPeriod(newPeriod as "daily" | "weekly" | "monthly");
  };

  return (
    <div className="bg-white rounded-xl border border-gray-300 shadow-sm p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-900">{t("dashboard.clientsOverTime")}</h3>
        <select
          value={period}
          onChange={(e) => handlePeriodChange(e.target.value)}
          className="px-3 py-1.5 text-sm text-gray-600 border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 cursor-pointer"
        >
          <option value="weekly">{t("dashboard.weekly")}</option>
          <option value="monthly">{t("dashboard.monthly")}</option>
          <option value="daily">{t("dashboard.daily")}</option>
        </select>
      </div>

      <div className="relative">
        {isLoading ? (
          <div className="flex items-center justify-center h-[250px]">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
          </div>
        ) : chartData.length === 0 ? (
          <div className="flex items-center justify-center h-[250px] text-gray-500">
            {t("dashboard.noData")}
          </div>
        ) : (
          <svg viewBox={`0 0 ${chartWidth} ${chartHeight}`} className="w-full h-auto">
            {/* Y-axis grid lines */}
            {yAxisTicks.map((tick) => (
              <g key={tick}>
                <line
                  x1={padding.left}
                  y1={padding.top + yScale(tick)}
                  x2={chartWidth - padding.right}
                  y2={padding.top + yScale(tick)}
                  stroke="#E5E7EB"
                  strokeDasharray="4,4"
                />
                <text
                  x={padding.left - 8}
                  y={padding.top + yScale(tick)}
                  textAnchor="end"
                  alignmentBaseline="middle"
                  className="text-xs fill-gray-400"
                >
                  {tick === 0 ? "0" : tick.toLocaleString()}
                </text>
              </g>
            ))}

            {/* Bars */}
            {chartData.map((d: any, i: number) => {
              const safeMaxValue = Math.max(maxValue, 1);
              const barHeight = Math.max(0, (d.value / safeMaxValue) * innerHeight);
              const x = xScale(i);
              const y = padding.top + innerHeight - barHeight;
              const isHovered = hoveredBar === i;

              return (
                <g key={i}>
                  <rect
                    x={x}
                    y={y}
                    width={barWidth}
                    height={barHeight || 1}
                    rx="8"
                    fill={isHovered ? "#3B9EC9" : "#E8F4F8"}
                    className="cursor-pointer transition-colors"
                    onMouseEnter={() => setHoveredBar(i)}
                    onMouseLeave={() => setHoveredBar(null)}
                  />
                  {isHovered && (
                    <g>
                      <rect
                        x={x + barWidth / 2 - 25}
                        y={y - 30}
                        width="50"
                        height="24"
                        rx="6"
                        fill="#3B9EC9"
                      />
                      <text
                        x={x + barWidth / 2}
                        y={y - 13}
                        textAnchor="middle"
                        className="text-xs fill-white font-medium"
                      >
                        {d.value}
                      </text>
                    </g>
                  )}
                  {/* X-axis label */}
                  <text
                    x={padding.left + (barSpacing / 2) + i * barSpacing}
                    y={chartHeight - 8}
                    textAnchor="middle"
                    className="text-xs fill-gray-400"
                  >
                    {d.label}
                  </text>
                </g>
              );
            })}
          </svg>
        )}
      </div>
    </div>
  );
}