"use client";

import { useQuery } from "@tanstack/react-query";
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer, PieChart, Pie, Cell,
} from "recharts";
import {
  CheckSquare, FolderOpen, TrendingUp, TrendingDown,
  Users, Target, Plus, Calendar, ArrowRight,
} from "lucide-react";
import Link from "next/link";
import { dashboardApi, transactionsApi } from "@/lib/api";
import { StatCard, ProgressBar, PriorityBadge, StatusBadge, Spinner, EmptyState } from "@/components/ui";
import { formatCurrency, formatDate, dueDateColor, truncate } from "@/lib/utils";
import { DashboardStats } from "@/types";

const MONTHS = ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"];

// Örnek grafik verisi (API bağlandığında dinamik olacak)
const CHART_COLORS = ["#3b82f6", "#22c55e", "#f59e0b", "#ef4444", "#a78bfa"];

export default function DashboardPage() {
  const year = new Date().getFullYear();

  const { data: stats, isLoading } = useQuery<DashboardStats>({
    queryKey: ["dashboard-stats"],
    queryFn: dashboardApi.getStats,
  });

  // Yıllık aylık gelir/gider verisi
  const { data: monthlyData } = useQuery({
    queryKey: ["monthly-chart", year],
    queryFn: async () => {
      const results = await Promise.all(
        Array.from({ length: 6 }, async (_, i) => {
          const month = new Date().getMonth() - 5 + i + 1;
          const adjustedMonth = ((month - 1 + 12) % 12) + 1;
          const adjustedYear = month <= 0 ? year - 1 : year;
          const summary = await transactionsApi.getSummary({ year: adjustedYear, month: adjustedMonth });
          return {
            name: MONTHS[adjustedMonth - 1],
            gelir: parseFloat(summary.total_income || "0"),
            gider: parseFloat(summary.total_expense || "0"),
          };
        })
      );
      return results;
    },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Spinner size={28} />
      </div>
    );
  }

  const s = stats!;
  const profit = parseFloat(s?.monthly_profit || "0");
  const income = parseFloat(s?.monthly_income || "0");
  const expense = parseFloat(s?.monthly_expense || "0");

  const pieData = [
    { name: "Gelir", value: income },
    { name: "Gider", value: expense },
  ];

  return (
    <div className="space-y-6 animate-fade-in">

      {/* ─── İstatistik Kartları ─── */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Toplam Görev"
          value={s?.total_tasks ?? 0}
          icon={<CheckSquare />}
          color="blue"
          subtitle={`Bugün ${s?.completed_tasks_today ?? 0} tamamlandı`}
        />
        <StatCard
          title="Aktif Proje"
          value={s?.active_projects ?? 0}
          icon={<FolderOpen />}
          color="purple"
        />
        <StatCard
          title="Bu Ay Gelir"
          value={formatCurrency(income)}
          icon={<TrendingUp />}
          color="green"
          subtitle={`Kâr: ${formatCurrency(profit)}`}
          trend={profit > 0 ? Math.round((profit / (income || 1)) * 100) : undefined}
        />
        <StatCard
          title="Bu Ay Gider"
          value={formatCurrency(expense)}
          icon={<TrendingDown />}
          color={expense > income ? "red" : "amber"}
          subtitle={`${s?.total_customers ?? 0} aktif müşteri`}
        />
      </div>

      {/* ─── Grafikler ─── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Alan Grafiği */}
        <div className="kaplan-card lg:col-span-2">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h3 className="text-sm font-semibold text-surface-100">Son 6 Aylık Gelir/Gider</h3>
              <p className="text-xs text-surface-500 mt-0.5">Finansal performans özeti</p>
            </div>
          </div>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={monthlyData || []}>
              <defs>
                <linearGradient id="gelir" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                </linearGradient>
                <linearGradient id="gider" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#ef4444" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="#ef4444" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#3a3a42" vertical={false} />
              <XAxis dataKey="name" tick={{ fill: "#8b8b98", fontSize: 11 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fill: "#8b8b98", fontSize: 11 }} axisLine={false} tickLine={false} tickFormatter={(v) => `₺${(v/1000).toFixed(0)}K`} />
              <Tooltip
                contentStyle={{ background: "#242428", border: "1px solid #3a3a42", borderRadius: "8px", fontSize: "12px" }}
                labelStyle={{ color: "#c4c4cc" }}
                formatter={(v: number) => [formatCurrency(v), ""]}
              />
              <Area type="monotone" dataKey="gelir" stroke="#3b82f6" strokeWidth={2} fill="url(#gelir)" name="Gelir" />
              <Area type="monotone" dataKey="gider" stroke="#ef4444" strokeWidth={2} fill="url(#gider)" name="Gider" />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Pie Chart */}
        <div className="kaplan-card">
          <h3 className="text-sm font-semibold text-surface-100 mb-1">Bu Ay Dağılım</h3>
          <p className="text-xs text-surface-500 mb-4">Gelir vs Gider</p>
          <ResponsiveContainer width="100%" height={140}>
            <PieChart>
              <Pie data={pieData} cx="50%" cy="50%" innerRadius={45} outerRadius={65} paddingAngle={4} dataKey="value">
                <Cell fill="#3b82f6" />
                <Cell fill="#ef4444" />
              </Pie>
              <Tooltip
                contentStyle={{ background: "#242428", border: "1px solid #3a3a42", borderRadius: "8px", fontSize: "12px" }}
                formatter={(v: number) => [formatCurrency(v), ""]}
              />
            </PieChart>
          </ResponsiveContainer>
          <div className="space-y-2 mt-2">
            <div className="flex items-center justify-between text-xs">
              <div className="flex items-center gap-2"><div className="w-2.5 h-2.5 rounded-full bg-blue-500" /><span className="text-surface-400">Gelir</span></div>
              <span className="text-surface-200 font-medium">{formatCurrency(income)}</span>
            </div>
            <div className="flex items-center justify-between text-xs">
              <div className="flex items-center gap-2"><div className="w-2.5 h-2.5 rounded-full bg-red-500" /><span className="text-surface-400">Gider</span></div>
              <span className="text-surface-200 font-medium">{formatCurrency(expense)}</span>
            </div>
            <div className="border-t border-surface-500 pt-2 flex justify-between text-xs">
              <span className="text-surface-400">Net Kâr</span>
              <span className={`font-semibold ${profit >= 0 ? "text-green-400" : "text-red-400"}`}>
                {formatCurrency(profit)}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* ─── Alt Bölüm ─── */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">

        {/* Yaklaşan Görevler */}
        <div className="kaplan-card">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-surface-100">Yaklaşan Görevler</h3>
            <Link href="/gorevler" className="text-xs text-brand-400 hover:text-brand-300 flex items-center gap-1">
              Tümü <ArrowRight size={12} />
            </Link>
          </div>
          {s?.upcoming_tasks?.length ? (
            <div className="space-y-2.5">
              {s.upcoming_tasks.map((task) => (
                <div key={task.id} className="flex items-center gap-3 p-2.5 bg-surface-800 rounded-lg">
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-surface-200 font-medium truncate">{task.title}</p>
                    <p className={`text-xs mt-0.5 ${dueDateColor(task.due_date)}`}>
                      {task.due_date ? formatDate(task.due_date) : "Tarih yok"}
                    </p>
                  </div>
                  <PriorityBadge priority={task.priority} />
                </div>
              ))}
            </div>
          ) : (
            <EmptyState icon="✅" title="Yaklaşan görev yok" />
          )}
        </div>

        {/* Son İşlemler */}
        <div className="kaplan-card">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-surface-100">Son Finansal İşlemler</h3>
            <Link href="/finans" className="text-xs text-brand-400 hover:text-brand-300 flex items-center gap-1">
              Tümü <ArrowRight size={12} />
            </Link>
          </div>
          {s?.recent_transactions?.length ? (
            <div className="space-y-2.5">
              {s.recent_transactions.map((tx) => (
                <div key={tx.id} className="flex items-center gap-3 p-2.5 bg-surface-800 rounded-lg">
                  <div className={`w-2 h-2 rounded-full flex-shrink-0 ${tx.type === "gelir" ? "bg-green-500" : "bg-red-500"}`} />
                  <div className="flex-1 min-w-0">
                    <p className="text-sm text-surface-200 truncate">{tx.description}</p>
                    <p className="text-xs text-surface-500">{formatDate(tx.date)}</p>
                  </div>
                  <span className={`text-sm font-semibold ${tx.type === "gelir" ? "text-green-400" : "text-red-400"}`}>
                    {tx.type === "gelir" ? "+" : "-"}{formatCurrency(parseFloat(tx.amount))}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState icon="💰" title="Henüz işlem yok" />
          )}
        </div>
      </div>

      {/* ─── Hızlı Erişim ─── */}
      <div className="kaplan-card">
        <h3 className="text-sm font-semibold text-surface-100 mb-4">Hızlı Erişim</h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          {[
            { href: "/gorevler", icon: "✅", label: "Yeni Görev", color: "bg-blue-500/10 hover:bg-blue-500/15 border-blue-500/20" },
            { href: "/projeler", icon: "🚀", label: "Yeni Proje", color: "bg-purple-500/10 hover:bg-purple-500/15 border-purple-500/20" },
            { href: "/finans", icon: "💰", label: "İşlem Ekle", color: "bg-green-500/10 hover:bg-green-500/15 border-green-500/20" },
            { href: "/notlar", icon: "📝", label: "Not Al", color: "bg-amber-500/10 hover:bg-amber-500/15 border-amber-500/20" },
          ].map(({ href, icon, label, color }) => (
            <Link key={href} href={href}>
              <div className={`flex items-center gap-3 p-3.5 rounded-xl border cursor-pointer transition-colors ${color}`}>
                <span className="text-xl">{icon}</span>
                <span className="text-sm font-medium text-surface-300">{label}</span>
              </div>
            </Link>
          ))}
        </div>
      </div>

    </div>
  );
}
