"use client";

import { useEffect, useState } from "react";
import {
  ResponsiveContainer,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
} from "recharts";
import useAxios from "@/hooks/useAxios";
import { useTranslation } from "react-i18next";

type SeriesPoint = {
  date: string;
  posts: number;
  followers: number;
  likes: number;
  comments: number;
};

type AnalyticsResponse = {
  range: string;
  series: SeriesPoint[];
  totals: {
    posts: number;
    followers: number;
    likes: number;
    comments: number;
  };
};

const RANGE_OPTIONS = ["7d", "30d", "90d", "all"] as const;
type RangeOption = (typeof RANGE_OPTIONS)[number];

export default function AccountAnalyticsWidget() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [range, setRange] = useState<RangeOption>("30d");
  const [data, setData] = useState<AnalyticsResponse | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    request<AnalyticsResponse>(
      "GET",
      `/account/analytics?range=${range}`,
      null,
      { noToast: true }
    )
      .then((res) => setData(res || null))
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, [request, range]);

  const totals = data?.totals;
  const series = data?.series || [];

  return (
    <div className="my-6 rounded-2xl border border-neutral-200 p-4 dark:border-neutral-800">
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <h3 className="text-sm font-bold">{t("settings.analytics.title")}</h3>
        <div className="flex gap-1 rounded-full bg-neutral-100 p-1 dark:bg-neutral-800">
          {RANGE_OPTIONS.map((opt) => (
            <button
              key={opt}
              type="button"
              onClick={() => setRange(opt)}
              className={`rounded-full px-3 py-1 text-xs font-semibold transition ${
                range === opt
                  ? "bg-white text-neutral-900 shadow dark:bg-neutral-700 dark:text-white"
                  : "text-neutral-500"
              }`}
            >
              {t(`settings.analytics.range.${opt}`)}
            </button>
          ))}
        </div>
      </div>

      <div className="mb-4 grid grid-cols-4 gap-2 text-center">
        <div>
          <p className="text-lg font-bold">{totals?.posts ?? 0}</p>
          <p className="text-[11px] text-neutral-500">
            {t("settings.analytics.metrics.posts")}
          </p>
        </div>
        <div>
          <p className="text-lg font-bold">{totals?.followers ?? 0}</p>
          <p className="text-[11px] text-neutral-500">
            {t("settings.analytics.metrics.followers")}
          </p>
        </div>
        <div>
          <p className="text-lg font-bold">{totals?.likes ?? 0}</p>
          <p className="text-[11px] text-neutral-500">
            {t("settings.analytics.metrics.likes")}
          </p>
        </div>
        <div>
          <p className="text-lg font-bold">{totals?.comments ?? 0}</p>
          <p className="text-[11px] text-neutral-500">
            {t("settings.analytics.metrics.comments")}
          </p>
        </div>
      </div>

      {loading ? (
        <div className="h-56 w-full animate-pulse rounded-xl bg-neutral-100 dark:bg-neutral-800" />
      ) : series.length === 0 ? (
        <p className="py-10 text-center text-sm text-neutral-500">
          {t("settings.analytics.empty")}
        </p>
      ) : (
        <div className="h-56 w-full">
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={series} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
              <CartesianGrid strokeDasharray="3 3" opacity={0.2} />
              <XAxis dataKey="date" tick={{ fontSize: 10 }} />
              <YAxis tick={{ fontSize: 10 }} allowDecimals={false} />
              <Tooltip />
              <Legend
                formatter={(value) =>
                  t(`settings.analytics.metrics.${value}`)
                }
                wrapperStyle={{ fontSize: 11 }}
              />
              <Line type="monotone" dataKey="posts" stroke="#6366f1" strokeWidth={2} dot={false} />
              <Line type="monotone" dataKey="followers" stroke="#10b981" strokeWidth={2} dot={false} />
              <Line type="monotone" dataKey="likes" stroke="#ec4899" strokeWidth={2} dot={false} />
              <Line type="monotone" dataKey="comments" stroke="#f59e0b" strokeWidth={2} dot={false} />
            </LineChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
}
