"use client";

import { useState, useEffect } from "react";
import { 
  Users, Receipt, ShoppingCart, DollarSign, 
  Settings, Clock, Ticket, TrendingUp, Loader2
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line, PieChart, Pie, Cell
} from "recharts";
import { toast } from "sonner";
import { fetchWithAuth } from "@/lib/api";

const MOCK_KPI_DATA = [
  { title: "Total Clients", value: "1,248", icon: Users, change: "+12%", trend: "up" },
  { title: "Total Revenue", value: "124,500 DZD", icon: DollarSign, change: "+18%", trend: "up" },
  { title: "Machines Sold", value: "142", icon: Settings, change: "+5%", trend: "up" },
  { title: "Pending Quotes", value: "24", icon: Receipt, change: "-2%", trend: "down" },
  { title: "Total Orders", value: "856", icon: ShoppingCart, change: "+8%", trend: "up" },
  { title: "Pending Requests", value: "12", icon: Clock, change: "0%", trend: "neutral" },
  { title: "Open Tickets", value: "8", icon: Ticket, change: "-4", trend: "down" },
  { title: "Monthly Growth", value: "14.2%", icon: TrendingUp, change: "+2.1%", trend: "up" },
];

const MOCK_REVENUE_DATA = [
  { name: "Jan", revenue: 4000 },
  { name: "Feb", revenue: 3000 },
  { name: "Mar", revenue: 5000 },
  { name: "Apr", revenue: 4500 },
  { name: "May", revenue: 6000 },
  { name: "Jun", revenue: 5500 },
  { name: "Jul", revenue: 7000 },
];

const MOCK_PRODUCT_CATEGORIES = [
  { name: "Industrial Shredders", value: 400 },
  { name: "Recycling Systems", value: 300 },
  { name: "Waste Management", value: 200 },
  { name: "Spare Parts", value: 100 },
];

const COLORS = ["#D80B17", "#ff4d4d", "#111827", "#4b5563"];

export default function DashboardHome() {
  const [loading, setLoading] = useState(true);
  const [kpiData, setKpiData] = useState<any[]>(MOCK_KPI_DATA);
  const [revenueData, setRevenueData] = useState<any[]>(MOCK_REVENUE_DATA);
  const [productCategories, setProductCategories] = useState<any[]>(MOCK_PRODUCT_CATEGORIES);

  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        setLoading(true);
        const data = await fetchWithAuth("/dashboard/summary");
        
        if (data) {
          // If the backend returns valid data, map it. Otherwise, use mock.
          if (data.kpiData) setKpiData(data.kpiData);
          if (data.revenueData) setRevenueData(data.revenueData);
          if (data.productCategories) setProductCategories(data.productCategories);
          toast.success("Dashboard data loaded successfully.");
        }
      } catch (error) {
        console.warn("Failed to fetch real dashboard data, falling back to mock data.", error);
        toast.error("Could not connect to API. Showing offline data.", {
          description: "Please check your KVM2 backend connection.",
        });
        // Keeping the MOCK data in state since it was initialized with it.
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-end">
        <div>
          <h2 className="text-3xl font-bold text-white tracking-tight">Dashboard Overview</h2>
          <p className="text-gray-400 mt-1">Welcome back, Super Admin. Here is what's happening today.</p>
        </div>
        {loading && (
          <div className="flex items-center text-gray-400">
            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            <span className="text-sm">Syncing with KVM2...</span>
          </div>
        )}
      </div>

      {/* KPI Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        {kpiData.map((kpi, index) => {
          const Icon = kpi.icon || Users; // Fallback icon
          return (
            <Card key={index} className="bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium text-gray-400">
                  {kpi.title}
                </CardTitle>
                {typeof Icon === "string" ? null : <Icon className="h-4 w-4 text-brand-red" />}
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-white">
                  {loading ? <div className="h-8 w-24 bg-white/10 rounded animate-pulse"></div> : kpi.value}
                </div>
                {!loading && (
                  <p className={`text-xs mt-1 ${
                    kpi.trend === "up" ? "text-emerald-400" : 
                    kpi.trend === "down" ? "text-brand-red" : "text-gray-400"
                  }`}>
                    {kpi.change} from last month
                  </p>
                )}
              </CardContent>
            </Card>
          );
        })}
      </div>

      {/* Charts Section */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-7">
        
        {/* Revenue Overview Line Chart */}
        <Card className="col-span-4 bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
          <CardHeader>
            <CardTitle className="text-white">Revenue Overview</CardTitle>
          </CardHeader>
          <CardContent className="pl-2">
            <div className="h-[300px] w-full mt-4 relative">
              {loading && (
                <div className="absolute inset-0 z-10 flex items-center justify-center bg-brand-charcoal/50 backdrop-blur-sm rounded-md">
                  <Loader2 className="w-8 h-8 text-brand-red animate-spin" />
                </div>
              )}
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={revenueData} margin={{ top: 5, right: 20, bottom: 5, left: 0 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#333" vertical={false} />
                  <XAxis dataKey="name" stroke="#888888" fontSize={12} tickLine={false} axisLine={false} />
                  <YAxis stroke="#888888" fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => `$${value}`} />
                  <Tooltip 
                    contentStyle={{ backgroundColor: "#111827", borderColor: "rgba(255,255,255,0.1)", color: "#fff" }}
                    itemStyle={{ color: "#D80B17" }}
                  />
                  <Line type="monotone" dataKey="revenue" stroke="#D80B17" strokeWidth={3} dot={{ r: 4, fill: "#D80B17" }} activeDot={{ r: 6 }} />
                </LineChart>
              </ResponsiveContainer>
            </div>
          </CardContent>
        </Card>

        {/* Product Categories Pie Chart */}
        <Card className="col-span-3 bg-brand-charcoal/50 border-white/10 backdrop-blur-sm">
          <CardHeader>
            <CardTitle className="text-white">Product Categories</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[300px] w-full flex items-center justify-center relative">
              {loading && (
                <div className="absolute inset-0 z-10 flex items-center justify-center bg-brand-charcoal/50 backdrop-blur-sm rounded-md">
                  <Loader2 className="w-8 h-8 text-brand-red animate-spin" />
                </div>
              )}
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={productCategories}
                    cx="50%"
                    cy="50%"
                    innerRadius={60}
                    outerRadius={100}
                    paddingAngle={5}
                    dataKey="value"
                    stroke="none"
                  >
                    {productCategories.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip 
                    contentStyle={{ backgroundColor: "#111827", borderColor: "rgba(255,255,255,0.1)", color: "#fff" }}
                  />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="flex flex-wrap justify-center gap-4 mt-2">
              {!loading && productCategories.map((entry, index) => (
                <div key={entry.name} className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[index % COLORS.length] }}></div>
                  <span className="text-xs text-gray-400">{entry.name}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
