// app/dashboard/page.tsx
"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Loader2, TrendingUp, TrendingDown, AlertTriangle } from "lucide-react";
import { axiosInstance } from "@/services/axios";
import { v4 as uuidv4 } from "uuid";
import { useRouter } from "next/navigation";
import { useToast } from "@/hooks/use-toast";
import { useDarkMode } from "@/app/context/ThemeContext";
import { AddCardModal } from "@/components/fundamental/addcard";

// Helper for delta style
const getDeltaStyle = (value: number) => {
  if (value > 3)
    return {
      bg: "bg-green-100",
      text: "text-green-700",
      icon: <TrendingUp className="w-4 h-4" />,
    };
  if (value < -3)
    return {
      bg: "bg-red-100",
      text: "text-red-700",
      icon: <TrendingDown className="w-4 h-4" />,
    };
  return {
    bg: "bg-yellow-100",
    text: "text-yellow-700",
    icon: <AlertTriangle className="w-4 h-4" />,
  };
};

export default function Dashboard() {
  // State declarations...
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newCardName, setNewCardName] = useState("");
  const [newCardOrgName, setNewCardOrgName] = useState("");
  const [adding, setAdding] = useState(false);
  const router = useRouter();
  const { toast } = useToast();
  const { darkMode } = useDarkMode();

  const [users, setUsers] = useState<any[]>([]);
  const [page, setPage] = useState<number>(1);
  const [loadingUsers, setLoadingUsers] = useState<boolean>(false);
  const limit = 10;

  const fetchUsers = async () => {
    setLoadingUsers(true);
    try {
      const response = await axiosInstance.get("/allUsers", {
        params: { page, limit },
      });
      if(response.data.data.length === 0) {
        toast({
          title: "End of list",
          description: "No more users to show",
          variant: "default",
        });
        return;
      }
      if (response.data && response.data.data) {
        setUsers(response.data.data);
      } else {
        toast({
          title: "Error",
          description: "Failed to load users",
          variant: "destructive",
        });
      }
    } catch (error) {
      console.error("Error fetching users:", error);
      toast({
        title: "Error",
        description: "Failed to fetch users",
        variant: "destructive",
      });
    } finally {
      setLoadingUsers(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [page]);

  const addCard = async () => {
    if (newCardName.trim() === "") return;
    try {
      setAdding(true);
      const respo = await axiosInstance.post("/saveInfo", {
        name: newCardName,
        userId: uuidv4(),
        type: "user",
        org_name: newCardOrgName,
        cluster: {},
        deltas: {},
      });
      if (respo.data?.data?.userId) {
        router.push(`/user/score/${respo.data.data.userId}`);
        toast({
          variant: "default",
          title: "Success",
          description: "Data source added successfully",
        });
      } else {
        setAdding(false);
        throw new Error("Invalid response from server");
      }
    } catch (e) {
      console.error("Error adding card:", e);
      toast({
        title: "Error",
        description: "Failed to add card",
        variant: "destructive",
      });
      setAdding(false);
    }
  };

  const goToNextPage = () => setPage((prev) => prev + 1);
  const goToPrevPage = () => {
    if (page > 1) setPage((prev) => prev - 1);
  };

  return (
    <div className="p-4 min-h-screen bg-gray-50 dark:bg-gray-900">
      <header className="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center px-3">
        <div className="mb-4 sm:mb-0">
          <h1 className="text-2xl font-bold mb-1 text-gray-800 dark:text-gray-100 capitalize">
            Dashboard
          </h1>
          <p className="text-base text-gray-600 dark:text-gray-300">
            View all data sources and performance scores
          </p>
        </div>
        <div>
          <AddCardModal
            isModalOpen={isModalOpen}
            setIsModalOpen={setIsModalOpen}
            newCardName={newCardName}
            setNewCardName={setNewCardName}
            newCardOrgName={newCardOrgName}
            setNewCardOrgName={setNewCardOrgName}
            addCard={addCard}
            adding={adding}
          />
        </div>
      </header>

      {loadingUsers ? (
        <div className="flex justify-center items-center py-8 min-h-screen">
          <Loader2 className="w-8 h-8 animate-spin" />
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {users.map((user) => {
            const deltaEntries = Object.entries(user.deltas || {});
            return (
              <Link
                key={user.userId}
                href={`/user/score/${user.userId}`}
                className="block"
              >
                <Card className="cursor-pointer transition hover:shadow-lg border rounded-md bg-white dark:bg-gray-800 h-full min-h-[230px]">
                  <CardContent className="p-4 flex flex-col justify-between h-full">
                    <div>
                      <h2 className="text-xl font-semibold mb-1 text-gray-800 dark:text-gray-200 capitalize">
                        {user.name}
                      </h2>
                      <p className="text-base text-gray-500 dark:text-gray-400 mb-3 capitalize">
                        {user.org_name}
                      </p>
                    </div>
                    {/* Responsive delta entries with flex layout */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-2 mt-1">
                      {deltaEntries.map(([key, value]) => {
                        const numValue = parseFloat(String(value));
                        const { bg, text, icon } = getDeltaStyle(numValue);
                        return (
                          <div
                            key={key}
                            className={`flex justify-between items-center p-2 rounded ${bg} ${text} text-xs`}
                          >
                            <span className="truncate capitalize">{key.replaceAll("_"," ")}</span>
                            <span className="flex items-center gap-1">
                              {icon}
                              <span>{numValue.toFixed(2)}</span>
                            </span>
                          </div>
                        );
                      })}
                    </div>
                  </CardContent>
                </Card>
              </Link>
            );
          })}
        </div>
      )}

      <div className="flex justify-between items-center mt-6">
        <Button onClick={goToPrevPage} disabled={page === 1} className="text-sm">
          Previous
        </Button>
        <span className="text-sm text-gray-700 dark:text-gray-300">Page {page}</span>
        <Button onClick={goToNextPage} className="text-sm">
          Next
        </Button>
      </div>
    </div>
  );
}
