"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { ShoppingBag, TrendingUp, Clock, Package, ArrowUpRight, ArrowDownRight } from "lucide-react";
import { dashboardApi } from "@/lib/api";

interface Stats {
  today_orders: number; today_revenue: number; pending_orders: number;
  total_orders: number; total_products: number; active_products: number;
  total_categories: number;
  weekly_data: Array<{ date: string; count: number; total: number }>;
  top_products: Array<{ product_name: string; total_quantity: number; total_revenue: number }>;
}

export default function AdminDashboard() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    dashboardApi.getStats()
      .then((res) => setStats(res.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const statCards = [
    { label: "Bugünkü Siparişler", value: stats?.today_orders || 0, icon: ShoppingBag, color: "text-primary", bg: "bg-primary/10" },
    { label: "Bugünkü Ciro", value: `₺${(stats?.today_revenue || 0).toLocaleString("tr-TR")}`, icon: TrendingUp, color: "text-emerald", bg: "bg-emerald/10" },
    { label: "Bekleyen Siparişler", value: stats?.pending_orders || 0, icon: Clock, color: "text-amber", bg: "bg-amber/10" },
    { label: "Aktif Ürünler", value: stats?.active_products || 0, icon: Package, color: "text-chart-5", bg: "bg-chart-5/10" },
  ];

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="bg-card rounded-xl border border-border/50 p-5 animate-pulse">
              <div className="h-4 bg-muted rounded w-1/2 mb-3" />
              <div className="h-8 bg-muted rounded w-1/3" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stat Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card, idx) => (
          <motion.div
            key={card.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
            className="bg-card rounded-xl border border-border/50 p-5 hover:shadow-lg hover:shadow-primary/5 transition-shadow"
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs text-muted-foreground font-medium">{card.label}</span>
              <div className={`w-8 h-8 rounded-lg ${card.bg} flex items-center justify-center`}>
                <card.icon className={`w-4 h-4 ${card.color}`} />
              </div>
            </div>
            <p className="text-2xl font-bold">{card.value}</p>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Weekly Revenue Chart (Simple Bar) */}
        <div className="bg-card rounded-xl border border-border/50 p-5">
          <h3 className="text-sm font-bold mb-4">Haftalık Ciro</h3>
          <div className="flex items-end gap-2 h-40">
            {(stats?.weekly_data || []).map((day, idx) => {
              const maxTotal = Math.max(...(stats?.weekly_data || []).map((d) => d.total), 1);
              const height = (day.total / maxTotal) * 100;
              return (
                <div key={idx} className="flex-1 flex flex-col items-center gap-1">
                  <span className="text-[10px] text-muted-foreground">₺{day.total.toLocaleString("tr-TR")}</span>
                  <motion.div
                    initial={{ height: 0 }}
                    animate={{ height: `${Math.max(height, 4)}%` }}
                    transition={{ delay: idx * 0.1, duration: 0.5 }}
                    className="w-full bg-gradient-to-t from-primary to-amber rounded-t-md min-h-[4px]"
                  />
                  <span className="text-[10px] text-muted-foreground">
                    {new Date(day.date).toLocaleDateString("tr-TR", { weekday: "short" })}
                  </span>
                </div>
              );
            })}
            {(!stats?.weekly_data || stats.weekly_data.length === 0) && (
              <div className="flex-1 text-center text-sm text-muted-foreground py-10">Henüz veri yok</div>
            )}
          </div>
        </div>

        {/* Top Products */}
        <div className="bg-card rounded-xl border border-border/50 p-5">
          <h3 className="text-sm font-bold mb-4">En Çok Sipariş Edilenler</h3>
          <div className="space-y-3">
            {(stats?.top_products || []).map((product, idx) => (
              <div key={idx} className="flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors">
                <span className="text-sm font-bold text-muted-foreground w-6">{idx + 1}.</span>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium truncate">{product.product_name}</p>
                  <p className="text-[10px] text-muted-foreground">{product.total_quantity} adet</p>
                </div>
                <span className="text-sm font-bold text-primary">₺{Number(product.total_revenue).toLocaleString("tr-TR")}</span>
              </div>
            ))}
            {(!stats?.top_products || stats.top_products.length === 0) && (
              <p className="text-sm text-muted-foreground text-center py-6">Henüz sipariş yok</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
