"use client";

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

const COLORS = ["#06b6d4", "#8b5cf6", "#3b82f6", "#6366f1"];

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 [mounted, setMounted] = useState(false);
  const { data, isLoading } = useDashboardStats();

  useEffect(() => {
    setMounted(true);
  }, []);

  // 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 (!mounted || 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-6 md:p-8 h-[300px] animate-pulse bg-[var(--color-bg-surface)] rounded-2xl border border-[var(--color-border-faint)]"
          />
        ))}
      </div>
    );
  }

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

      {/* Proje Durumu */}
      <div className="card-surface p-6 md:p-8 flex flex-col">
        <h3 className="text-base font-semibold text-[var(--color-text-secondary)] mb-2">
          Proje Durumu
        </h3>
        {pieData.length === 0 ? (
          <div className="flex flex-1 items-center justify-center text-sm text-[var(--color-text-ghost)]">
            Henüz proje verisi yok
          </div>
        ) : (
          <div className="flex flex-1 flex-row items-center justify-center gap-4 sm:gap-8 min-h-[220px]">
            <div className="w-[160px] h-[160px] sm:w-[200px] sm:h-[200px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={pieData}
                    cx="50%"
                    cy="50%"
                    outerRadius="85%"
                    innerRadius="65%"
                    dataKey="value"
                    stroke="var(--color-bg-surface)"
                    strokeWidth={3}
                    paddingAngle={4}
                  >
                    {pieData.map((_: unknown, index: number) => (
                      <Cell key={index} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip
                    contentStyle={{
                      backgroundColor: "rgba(10,10,10,0.95)",
                      border: "1px solid rgba(255,255,255,0.1)",
                      borderRadius: 12,
                      fontSize: 13,
                      color: "#fff",
                      boxShadow: "0 4px 20px rgba(0,0,0,0.3)"
                    }}
                    itemStyle={{
                      color: "#e5e5e5"
                    }}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="flex flex-col justify-center space-y-3">
              {pieData.map((item: { name: string; value: number }, idx: number) => (
                <div key={item.name} className="flex items-center gap-3">
                  <div
                    className="w-3 h-3 rounded-full shadow-sm"
                    style={{ backgroundColor: COLORS[idx % COLORS.length], boxShadow: `0 0 8px ${COLORS[idx % COLORS.length]}80` }}
                  />
                  <div className="flex flex-col">
                    <span className="text-sm text-[var(--color-text-muted)] font-medium leading-none mb-1">
                      {item.name}
                    </span>
                    <span className="text-base font-bold text-[var(--color-text-primary)] leading-none">
                      {item.value}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
