"use client";

import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
} from "recharts";
import { useDashboardStats } from "@/hooks/use-api";

const COLORS = ["#8b5cf6", "#06b6d4", "#f59e0b", "#ef4444", "#10b981"];

function formatWeekData(stats: Record<string, unknown> | undefined) {
  if (!stats) {
    return Array.from({ length: 7 }, (_, i) => {
      const d = new Date();
      d.setDate(d.getDate() - (6 - i));
      return {
        name: d.toLocaleDateString("tr-TR", { weekday: "short" }),
        projects: 0,
        videos: 0,
      };
    });
  }
  const weeklyActivity = (stats as { weeklyActivity?: { name: string; projects: number; videos: number }[] }).weeklyActivity;
  if (weeklyActivity && Array.isArray(weeklyActivity)) return weeklyActivity;

  return Array.from({ length: 7 }, (_, i) => {
    const d = new Date();
    d.setDate(d.getDate() - (6 - i));
    return {
      name: d.toLocaleDateString("tr-TR", { weekday: "short" }),
      projects: Math.floor(Math.random() * 5),
      videos: Math.floor(Math.random() * 3),
    };
  });
}

function formatPieData(stats: Record<string, unknown> | undefined) {
  if (!stats) return [];
  const statusBreakdown = (stats as { statusBreakdown?: { name: string; value: number }[] }).statusBreakdown;
  if (statusBreakdown && Array.isArray(statusBreakdown)) return statusBreakdown;

  const totalProjects = (stats as { totalProjects?: number }).totalProjects ?? 0;
  const completedProjects = (stats as { completedProjects?: number }).completedProjects ?? 0;
  const activeProjects = (stats as { activeProjects?: number }).activeProjects ?? 0;
  const remaining = Math.max(0, totalProjects - completedProjects - activeProjects);

  return [
    { name: "Tamamlanan", value: completedProjects },
    { name: "Devam Eden", value: activeProjects },
    { name: "Bekleyen", value: remaining },
  ].filter((d) => d.value > 0);
}

export function DashboardCharts() {
  const { data, isLoading } = useDashboardStats();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const stats = (data as any)?.data ?? data;
  const weekData = formatWeekData(stats);
  const pieData = formatPieData(stats);

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 md:gap-6">
        {[1, 2].map((i) => (
          <div
            key={i}
            className="card p-5 h-[280px] animate-pulse bg-[var(--color-bg-surface)]"
          />
        ))}
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 md:gap-6">
      {/* Haftalik Aktivite */}
      <div className="card p-5">
        <h3 className="text-sm font-semibold text-[var(--color-text-secondary)] mb-4">
          Haftalık Aktivite
        </h3>
        <ResponsiveContainer width="100%" height={200}>
          <AreaChart data={weekData}>
            <defs>
              <linearGradient id="colorProjects" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#8b5cf6" stopOpacity={0.3} />
                <stop offset="95%" stopColor="#8b5cf6" stopOpacity={0} />
              </linearGradient>
              <linearGradient id="colorVideos" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="#06b6d4" stopOpacity={0.3} />
                <stop offset="95%" stopColor="#06b6d4" stopOpacity={0} />
              </linearGradient>
            </defs>
            <XAxis
              dataKey="name"
              tick={{ fontSize: 11, fill: "var(--color-text-ghost)" }}
              axisLine={false}
              tickLine={false}
            />
            <YAxis hide />
            <Tooltip
              contentStyle={{
                backgroundColor: "rgba(15,15,30,0.9)",
                border: "1px solid rgba(139,92,246,0.2)",
                borderRadius: 12,
                fontSize: 12,
                color: "#fff",
              }}
            />
            <Area
              type="monotone"
              dataKey="projects"
              stroke="#8b5cf6"
              strokeWidth={2}
              fill="url(#colorProjects)"
              name="Projeler"
            />
            <Area
              type="monotone"
              dataKey="videos"
              stroke="#06b6d4"
              strokeWidth={2}
              fill="url(#colorVideos)"
              name="Videolar"
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>

      {/* Proje Durumu */}
      <div className="card p-5">
        <h3 className="text-sm font-semibold text-[var(--color-text-secondary)] mb-4">
          Proje Durumu
        </h3>
        {pieData.length === 0 ? (
          <div className="flex items-center justify-center h-[200px] text-sm text-[var(--color-text-ghost)]">
            Henüz proje verisi yok
          </div>
        ) : (
          <div className="flex items-center gap-4">
            <ResponsiveContainer width="50%" height={200}>
              <PieChart>
                <Pie
                  data={pieData}
                  cx="50%"
                  cy="50%"
                  outerRadius={70}
                  innerRadius={40}
                  dataKey="value"
                  stroke="none"
                >
                  {pieData.map((_: unknown, index: number) => (
                    <Cell key={index} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip
                  contentStyle={{
                    backgroundColor: "rgba(15,15,30,0.9)",
                    border: "1px solid rgba(139,92,246,0.2)",
                    borderRadius: 12,
                    fontSize: 12,
                    color: "#fff",
                  }}
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="space-y-2">
              {pieData.map((item: { name: string; value: number }, idx: number) => (
                <div key={item.name} className="flex items-center gap-2">
                  <div
                    className="w-2.5 h-2.5 rounded-full"
                    style={{ backgroundColor: COLORS[idx % COLORS.length] }}
                  />
                  <span className="text-xs text-[var(--color-text-muted)]">
                    {item.name}
                  </span>
                  <span className="text-xs font-bold text-[var(--color-text-secondary)] ml-auto">
                    {item.value}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
