import {
  Building2,
  ChevronDown,
  ChevronUp,
  CirclePause,
  DollarSign,
  Funnel,
  PickaxeIcon,
  RefreshCw,
  UserIcon,
  UsersIcon,
  Wrench,
} from "lucide-react";
import moment from "moment-jalaali";
import { useCallback, useEffect, useRef, useState } from "react";
import toast from "react-hot-toast";
import { Badge } from "~/components/ui/badge";
import { BaseCard } from "~/components/ui/base-card";
import { Button } from "~/components/ui/button";
import { Card, CardContent } from "~/components/ui/card";
import { Checkbox } from "~/components/ui/checkbox";
import { CustomBarChart } from "~/components/ui/custom-bar-chart";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "~/components/ui/table";
import apiService from "~/lib/api";
import { formatNumber } from "~/lib/utils";
import { DashboardLayout } from "../layout";

moment.loadPersian({ usePersianDigits: true });
interface ProcessInnovationData {
  project_no: string;
  project_id: string;
  title: string;
  project_status: string;
  project_rating: string;
  reduce_prevention_production_stops: string;
  throat_removal: string;
  amount_currency_reduction: string;
  Reduce_rate_failure: string;
  observer: string;
  // optional detailed fields returned by API
  project_description?: string;
  start_date?: string;
  done_date?: string;
  approved_budget?: string;
}

interface ProjectStats {
  average_project_score: string;
  count_innovation_process_projects: number;
  count_throat_removal: number;
  percent_reducing_breakdowns: string;
  percent_reduction_value_currency: string;
  percent_sum_stopping_production: string;
  percent_throat_removal: string;
  sum_reducing_breakdowns: number;
  sum_reduction_value_currency: number;
  sum_stopping_production: number;
}

interface SortConfig {
  field: string;
  direction: "asc" | "desc";
}

enum projectStatus {
  propozal = "پروپوزال",
  contract = "پیشنویس قرارداد",
  inprogress = "در حال انجام",
  stop = "متوقف شده",
  mafasa = "مرحله مفاصا",
  finish = "پایان یافته",
}

interface InnovationStats {
  totalProjects: number;
  averageScore: number;
  productionStopsPreventionSum: number; // مجموع جلوگیری از توقفات تولید
  bottleneckRemovalCount: number; // تعداد رفع گلوگاه
  currencyReductionSum: number; // مجموع کاهش ارز بری (میلیون ریال)
  frequentFailuresReductionSum: number; // مجموع کاهش خرابی های پرتکرار
  percentProductionStops: number | string; // درصد مقایسه‌ای جلوگیری از توقفات تولید
  percentBottleneckRemoval: number | string; // درصد مقایسه‌ای رفع گلوگاه
  percentCurrencyReduction: number | string; // درصد مقایسه‌ای کاهش ارز بری
  percentFailuresReduction: number | string; // درصد مقایسه‌ای کاهش خرابی‌های پرتکرار
}

const columns = [
  { key: "select", label: "", sortable: false, width: "50px" },
  { key: "project_no", label: "شماره پروژه", sortable: true, width: "140px" },
  { key: "title", label: "عنوان پروژه", sortable: true, width: "400px" },
  {
    key: "project_status",
    label: "وضعیت پروژه",
    sortable: true,
    width: "140px",
  },
  {
    key: "project_rating",
    label: "امتیاز پروژه",
    sortable: true,
    width: "140px",
  },
  { key: "details", label: "جزئیات پروژه", sortable: false, width: "140px" },
];

export function ProcessInnovationPage() {
  const [projects, setProjects] = useState<ProcessInnovationData[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [hasMore, setHasMore] = useState(true);
  const [totalCount, setTotalCount] = useState(0);
  const [actualTotalCount, setActualTotalCount] = useState(0);
  const [statsLoading, setStatsLoading] = useState(false);
  const [stats, setStats] = useState<InnovationStats>({
    totalProjects: 0,
    averageScore: 0,
    productionStopsPreventionSum: 0,
    bottleneckRemovalCount: 0,
    currencyReductionSum: 0,
    frequentFailuresReductionSum: 0,
    percentProductionStops: 0,
    percentBottleneckRemoval: 0,
    percentCurrencyReduction: 0,
    percentFailuresReduction: 0,
  });
  const [sortConfig, setSortConfig] = useState<SortConfig>({
    field: "start_date",
    direction: "asc",
  });
  const [selectedProjects, setSelectedProjects] = useState<Set<string>>(
    new Set()
  );
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  const [selectedProjectDetails, setSelectedProjectDetails] =
    useState<ProcessInnovationData | null>(null);

  const [stateCard, setStateCard] = useState({
    productionstopsprevention: {
      id: "productionstopsprevention",
      title: "جلوگیری از توقفات تولید",
      value: formatNumber(
        stats.productionStopsPreventionSum.toFixed?.(1) ??
          stats.productionStopsPreventionSum
      ),
      description: "تن افزایش یافته",
      icon: CirclePause,
      color: "text-emerald-400",
    },
    bottleneckremoval: {
      id: "bottleneckremoval",
      title: "رفع گلوگاه",
      value: formatNumber(stats.bottleneckRemovalCount),
      description: "تعداد رفع گلوگاه",
      icon: Funnel,
      color: "text-emerald-400",
    },
    currencyreduction: {
      id: "currencyreduction",
      title: "کاهش ارز بری",
      value: formatNumber(
        stats.currencyReductionSum.toFixed?.(0) ?? stats.currencyReductionSum
      ),
      description: "دلار کاهش یافته",
      icon: DollarSign,
      color: "text-emerald-400",
    },
    frequentfailuresreduction: {
      id: "frequentfailuresreduction",
      title: "کاهش خرابی های پرتکرار",
      value: formatNumber(
        stats.frequentFailuresReductionSum.toFixed?.(1) ??
          stats.frequentFailuresReductionSum
      ),
      description: "مجموع درصد کاهش خرابی",
      icon: Wrench,
      color: "text-emerald-400",
    },
  });

  const observerRef = useRef<HTMLDivElement>(null);
  const fetchingRef = useRef(false);

  // Selection handlers
  const handleSelectAll = () => {
    if (selectedProjects.size === projects.length) {
      setSelectedProjects(new Set());
    } else {
      setSelectedProjects(new Set(projects.map((p) => p.project_no)));
    }
  };

  const handleSelectProject = (projectNo: string) => {
    const newSelected = new Set(selectedProjects);
    if (newSelected.has(projectNo)) {
      newSelected.delete(projectNo);
    } else {
      newSelected.add(projectNo);
    }
    setSelectedProjects(newSelected);
  };

  const handleProjectDetails = (project: ProcessInnovationData) => {
    setSelectedProjectDetails(project);
    setDetailsDialogOpen(true);
  };

  // Stats cards data - computed from projects data
  const fetchProjects = async (reset = false) => {
    if (fetchingRef.current) {
      return;
    }

    try {
      fetchingRef.current = true;

      if (reset) {
        setLoading(true);
        setCurrentPage(1);
      } else {
        setLoadingMore(true);
      }

      const pageToFetch = reset ? 1 : currentPage;

      const response = await apiService.select({
        ProcessName: "project",
        OutputFields: [
          "project_no",
          "project_id",
          "title",
          "project_status",
          "project_rating",
          "throat_removal",
          "reduce_prevention_production_stops",
          "amount_currency_reduction",
          "Reduce_rate_failure",
          "project_description",
          "start_date",
          "done_date",
          "approved_budget",
          "observer",
        ],
        Sorts: [["start_date", "asc"]],
        Conditions: [["type_of_innovation", "=", "نوآوری در فرآیند"]],
        Pagination: { PageNumber: pageToFetch, PageSize: pageSize },
      });

      if (response.state === 0) {
        const dataString = response.data;
        if (dataString && typeof dataString === "string") {
          try {
            const parsedData = JSON.parse(dataString);
            if (Array.isArray(parsedData)) {
              if (reset) {
                setProjects(parsedData);
                setTotalCount(parsedData.length);
              } else {
                setProjects((prev) => [...prev, ...parsedData]);
                setTotalCount((prev) => prev + parsedData.length);
              }
              setHasMore(parsedData.length === pageSize);
            } else {
              if (reset) {
                setProjects([]);
                setTotalCount(0);
              }
              setHasMore(false);
            }
          } catch (parseError) {
            console.error("Error parsing project data:", parseError);
            if (reset) {
              setProjects([]);
              setTotalCount(0);
            }
            setHasMore(false);
          }
        } else {
          if (reset) {
            setProjects([]);
            setTotalCount(0);
          }
          setHasMore(false);
        }
      } else {
        toast.error(response.message || "خطا در دریافت اطلاعات پروژه‌ها");
        if (reset) {
          setProjects([]);
          setTotalCount(0);
        }
        setHasMore(false);
      }
    } catch (error) {
      console.error("Error fetching projects:", error);
      toast.error("خطا در دریافت اطلاعات پروژه‌ها");
      if (reset) {
        setProjects([]);
        setTotalCount(0);
      }
      setHasMore(false);
    } finally {
      setLoading(false);
      setLoadingMore(false);
      fetchingRef.current = false;
    }
  };

  const loadMore = useCallback(() => {
    if (hasMore && !loading) {
      setCurrentPage((prev) => prev + 1);
    }
  }, [hasMore, loading]);

  useEffect(() => {
    fetchProjects(true);
    fetchTotalCount();
  }, [sortConfig]);

  useEffect(() => {
    fetchStats();
  }, [selectedProjects]);

  useEffect(() => {
    if (currentPage > 1) {
      fetchProjects(false);
    }
  }, [currentPage]);

  useEffect(() => {
    const scrollContainer = document.querySelector(".overflow-auto");

    const handleScroll = () => {
      if (!scrollContainer || !hasMore) return;

      const { scrollTop, scrollHeight, clientHeight } = scrollContainer;
      const scrollPercentage = (scrollTop + clientHeight) / scrollHeight;

      if (scrollPercentage == 1) {
        loadMore();
      }
    };

    if (scrollContainer) {
      scrollContainer.addEventListener("scroll", handleScroll);
    }

    return () => {
      if (scrollContainer) {
        scrollContainer.removeEventListener("scroll", handleScroll);
      }
    };
  }, [loadMore, hasMore, loadingMore]);

  const handleSort = (field: string) => {
    fetchingRef.current = false;
    setSortConfig((prev) => ({
      field,
      direction:
        prev.field === field && prev.direction === "asc" ? "desc" : "asc",
    }));
    setCurrentPage(1);
    setProjects([]);
    setHasMore(true);
  };

  const fetchTotalCount = async () => {
    try {
      const response = await apiService.select({
        ProcessName: "project",
        OutputFields: ["count(project_no)"],
        Conditions: [["type_of_innovation", "=", "نوآوری در فرآیند"]],
      });

      if (response.state === 0) {
        const dataString = response.data;
        if (dataString && typeof dataString === "string") {
          try {
            const parsedData = JSON.parse(dataString);
            if (Array.isArray(parsedData) && parsedData[0]) {
              const count = parsedData[0].project_no_count || 0;
              setActualTotalCount(count);
              // Keep stats in sync if backend stats not yet loaded
              setStats((prev) => ({ ...prev, totalProjects: count }));
            }
          } catch (parseError) {
            console.error("Error parsing count data:", parseError);
          }
        }
      }
    } catch (error) {
      console.error("Error fetching total count:", error);
    }
  };

  // Fetch aggregated stats from backend call API (innovation_process_function)
  const fetchStats = async () => {
    try {
      setStatsLoading(true);
      const raw = await apiService.call<any>({
        innovation_process_function: {
          project_ids:
            selectedProjects.size > 0
              ? Array.from(selectedProjects).join(" , ")
              : "",
        },
      });

      let payload: any = raw?.data;
      if (typeof payload === "string") {
        try {
          payload = JSON.parse(payload);
        } catch {}
      }

      const parseNum = (v: unknown): any => {
        const convertNumber = typeof v === "number" ? Math.max(0, v) : 0;
        if (v == null) return 0;
        if (typeof v === "number") return convertNumber;
        if (typeof v === "string") {
          const cleaned = v.replace(/,/g, "").trim();
          const n = parseFloat(cleaned);
          return isNaN(n) ? 0 : convertNumber;
        }
        return 0;
      };

      const data: Array<ProjectStats> = JSON.parse(
        payload?.innovation_process_function
      );
      const stats = data[0];
      const normalized: InnovationStats = {
        totalProjects: parseNum(stats?.count_innovation_process_projects),
        averageScore: parseFloat(data[0].average_project_score),
        productionStopsPreventionSum: parseNum(stats?.sum_stopping_production),
        bottleneckRemovalCount: parseNum(stats?.count_throat_removal),
        currencyReductionSum: parseNum(stats?.sum_reduction_value_currency),
        frequentFailuresReductionSum: parseNum(stats?.sum_reducing_breakdowns),
        percentProductionStops: stats?.percent_sum_stopping_production,
        percentBottleneckRemoval: stats?.percent_throat_removal,
        percentCurrencyReduction: stats?.percent_reduction_value_currency,
        percentFailuresReduction: stats?.percent_reducing_breakdowns,
      };
      setStateCard((prev) => ({
        ...prev,
        bottleneckremoval: {
          ...prev.bottleneckremoval,
          value: formatNumber(normalized.bottleneckRemovalCount),
        },
        productionstopsprevention: {
          ...prev.productionstopsprevention,
          value: formatNumber(normalized.productionStopsPreventionSum),
        },
        frequentfailuresreduction: {
          ...prev.frequentfailuresreduction,
          value: formatNumber(normalized.frequentFailuresReductionSum),
        },
        currencyreduction: {
          ...prev.currencyreduction,
          value: formatNumber(normalized.currencyReductionSum),
        },
      }));
      setStats(normalized);
    } catch (error) {
      console.error("Error fetching stats:", error);
    } finally {
      setStatsLoading(false);
    }
  };

  const formatCurrency = (amount: string | number) => {
    if (!amount) return "0 ریال";
    const numericAmount =
      typeof amount === "string"
        ? parseFloat(amount.replace(/,/g, ""))
        : amount;
    if (isNaN(numericAmount)) return "0 ریال";
    return new Intl.NumberFormat("fa-IR").format(numericAmount) + " ریال";
  };

  const statusColor = (status: projectStatus): any => {
    let el = null;
    switch (status) {
      case projectStatus.contract:
        el = "teal";
        break;
      case projectStatus.finish:
        el = "info";
        break;
      case projectStatus.stop:
        el = "warning";
        break;
      case projectStatus.inprogress:
        el = "teal";
        break;
      case projectStatus.mafasa:
        el = "destructive";
        break;
      case projectStatus.propozal:
        el = "info";
    }
    return el;
  };

  const renderCellContent = (item: ProcessInnovationData, column: any) => {
    const value = item[column.key as keyof ProcessInnovationData];

    switch (column.key) {
      case "select":
        return (
          <Checkbox
            checked={selectedProjects.has(item.project_id)}
            onCheckedChange={() => handleSelectProject(item.project_id)}
            className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
          />
        );
      case "details":
        return (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => handleProjectDetails(item)}
            className="text-pr-green hover:text-emerald-300 underline-offset-4 underline font-normal hover:bg-emerald-500/20 p-2 h-auto"
          >
            جزئیات بیشتر
          </Button>
        );
      case "amount_currency_reduction":
        return (
          <span className="font-medium text-emerald-400">
            {formatCurrency(String(value))}
          </span>
        );
      case "project_no":
        return (
          <Badge variant="outline" className="font-normal text-sm">
            {String(value)}
          </Badge>
        );
      case "title":
        return (
          <span className="font-normal text-sm text-white">
            {String(value)}
          </span>
        );
      case "project_status":
        return (
          <div className="flex items-center gap-1">
            <Badge
              variant={statusColor(value as projectStatus)}
              className="font-normal text-base border-2 p-0 block w-2 h-2 rounded-full"
              style={{
                border: "none",
              }}
            ></Badge>
            {String(value)}
          </div>
        );
      case "project_rating":
        return (
          <Badge
            variant="outline"
            className="text-base font-semibold text-center border-none"
          >
            {formatNumber(String(value))}
          </Badge>
        );
      case "reduce_prevention_production_stops":
      case "throat_removal":
      case "Reduce_rate_failure":
        return (
          <span className="font-medium text-blue-400">
            {formatNumber(String(value))}
          </span>
        );
      default:
        return <span className="text-gray-300">{String(value) || "-"}</span>;
    }
  };

  return (
    <DashboardLayout title="نوآوری در فرآیند">
      <div className="py-2 space-y-4">
        {/* Stats Cards */}
        <div className="flex gap-6">
          <div className="space-y-4 w-full">
            {/* Stats Grid */}
            <div className="grid grid-cols-2 gap-3">
              {loading || statsLoading
                ? // Loading skeleton for stats cards - matching new design
                  Array.from({ length: 4 }).map((_, index) => (
                    <BaseCard
                      key={`skeleton-${index}`}
                      className="rounded-2xl overflow-hidden"
                    >
                      <div className="flex flex-col justify-between gap-2">
                        <div className="flex justify-between items-center border-b-2 mx-4 border-gray-500/20">
                          <div
                            className="h-6 bg-gray-600 rounded animate-pulse"
                            style={{ width: "60%" }}
                          />
                          <div className="p-3 bg-emerald-500/20 rounded-full w-fit">
                            <div className="w-6 h-6 bg-gray-600 rounded animate-pulse" />
                          </div>
                        </div>
                        <div className="flex items-center justify-center flex-col p-1">
                          <div
                            className="h-8 bg-gray-600 rounded mb-1 animate-pulse"
                            style={{ width: "40%" }}
                          />
                          <div
                            className="h-4 bg-gray-600 rounded animate-pulse"
                            style={{ width: "80%" }}
                          />
                        </div>
                      </div>
                    </BaseCard>
                  ))
                : Object.entries(stateCard).map(([key, card]) => {
                    // map percent values for each card key
                    const percentMap: Record<
                      string,
                      number | string | undefined
                    > = {
                      productionstopsprevention: stats.percentProductionStops,
                      bottleneckremoval: stats.percentBottleneckRemoval,
                      currencyreduction: stats.percentCurrencyReduction,
                      frequentfailuresreduction: stats.percentFailuresReduction,
                    };
                    const percentValue = percentMap[key];

                    return (
                      <BaseCard
                        key={card.id}
                        title={card.title}
                        className="border-gray-700/50"
                        icon={card.icon}
                      >
                        <div className="flex items-center justify-center flex-col">
                          <div className="flex items-center gap-4">
                            <div className="text-center">
                              <p className="text-3xl text-pr-green font-bold mb-1">
                                {card.value}
                              </p>
                              <div className="text-[11px] text-[#ACACAC] font-light font-persian">
                                {card.description}
                              </div>
                            </div>
                          </div>
                        </div>
                      </BaseCard>
                    );
                  })}
            </div>
          </div>

          {/* Process Impacts Chart */}
          {/* نمودار با الگوریتم Nice Numbers:
              مثلاً اگر داده‌ها [10, 35, 63, 18] باشند:
              - حداکثر: 63، با حاشیه 5% = 66.15
              - Nice Max: 75 (گرد و خوانا)  
              - Ticks: [0, 20, 40, 60, 75]
              این باعث می‌شود نمودار زیباتر و خوانا‌تر باشد */}
          <BaseCard className="rounded-2xl w-full overflow-hidden">
            <CustomBarChart
              title="تاثیرات فرآیندی به صورت درصد مقایسه ای"
              loading={statsLoading}
              data={[
                {
                  label: "کاهش توقفات تولید",
                  value: Number(stats.percentProductionStops) || 0,
                  labelColor: "text-white",
                },
                {
                  label: "رفع گلوگاه تولید",
                  value: Number(stats.percentBottleneckRemoval) || 0,
                  labelColor: "text-white",
                },
                {
                  label: "کاهش ارز بری",
                  value: Number(stats.percentCurrencyReduction) || 0,
                  labelColor: "text-white",
                },
                {
                  label: "کاهش خرابی پر تکرار",
                  value: Number(stats.percentFailuresReduction) || 0,
                  labelColor: "text-white",
                },
              ]}
              barHeight="h-6"
              showAxisLabels={true}
            />
          </BaseCard>
        </div>

        {/* Data Table */}
        <Card className="bg-transparent backdrop-blur-sm rounded-2xl overflow-hidden">
          <CardContent className="p-0">
            <div className="relative">
              <Table containerClassName="overflow-auto custom-scrollbar max-h-[calc(90vh-400px)]">
                <TableHeader>
                  <TableRow className="bg-[#3F415A]">
                    {columns.map((column) => (
                      <TableHead
                        key={column.key}
                        className="text-right font-persian whitespace-nowrap text-gray-200 font-medium sticky top-0 z-20 bg-[#3F415A]"
                        style={{ width: column.width }}
                      >
                        {column.key === "select" ? (
                          <div className="flex items-center justify-center">
                            <Checkbox
                              checked={
                                selectedProjects.size === projects.length &&
                                projects.length > 0
                              }
                              onCheckedChange={handleSelectAll}
                              className="data-[state=checked]:bg-emerald-600 data-[state=checked]:border-emerald-600"
                            />
                          </div>
                        ) : column.sortable ? (
                          <button
                            onClick={() => handleSort(column.key)}
                            className="flex items-center gap-2"
                          >
                            <span>{column.label}</span>
                            {sortConfig.field === column.key ? (
                              sortConfig.direction === "asc" ? (
                                <ChevronUp className="w-4 h-4" />
                              ) : (
                                <ChevronDown className="w-4 h-4" />
                              )
                            ) : (
                              <div className="w-4 h-4" />
                            )}
                          </button>
                        ) : (
                          column.label
                        )}
                      </TableHead>
                    ))}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {loading ? (
                    // Skeleton loading rows (compact)
                    Array.from({ length: 10 }).map((_, index) => (
                      <TableRow
                        key={`skeleton-${index}`}
                        className="text-sm leading-tight h-8"
                      >
                        {columns.map((column) => (
                          <TableCell
                            key={column.key}
                            className="text-right whitespace-nowrap border-emerald-500/20 py-1 px-2"
                          >
                            <div className="flex items-center gap-2">
                              <div className="w-2.5 h-2.5 bg-gray-600 rounded-full animate-pulse" />
                              <div
                                className="h-2.5 bg-gray-600 rounded animate-pulse"
                                style={{ width: `${Math.random() * 60 + 40}%` }}
                              />
                            </div>
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : projects.length === 0 ? (
                    <TableRow>
                      <TableCell
                        colSpan={columns.length}
                        className="text-center py-8"
                      >
                        <span className="text-gray-400 font-persian">
                          هیچ پروژه‌ای یافت نشد
                        </span>
                      </TableCell>
                    </TableRow>
                  ) : (
                    projects.map((project, index) => (
                      <TableRow
                        key={`${project.project_no}-${index}`}
                        className="text-sm leading-tight h-8"
                      >
                        {columns.map((column) => (
                          <TableCell
                            key={column.key}
                            className={`text-right whitespace-nowrap border-emerald-500/20 py-1 px-2 ${column.key === "select" ? "flex justify-center items-center" : ""}`}
                          >
                            {renderCellContent(project, column)}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>

            {/* Infinite scroll trigger */}
            <div ref={observerRef} className="h-auto">
              {loadingMore && (
                <div className="flex items-center justify-center py-1">
                  <div className="flex items-center gap-2">
                    <RefreshCw className="w-4 h-4 animate-spin text-emerald-400" />
                    <span className="font-persian text-gray-300 text-xs"></span>
                  </div>
                </div>
              )}
            </div>
          </CardContent>

          {/* Footer */}

          <div className="p-2 px-4 bg-[#3F415A]">
            <div className="flex gap-4 text-sm text-gray-300 font-persian justify-between sm:flex-col xl:flex-row">
              <div className="text-center gap-2 items-center  xl:w-1/3 pr-36 sm:w-full">
                <div className="text-base text-gray-401 mb-1">
                  کل پروژه ها :{formatNumber(actualTotalCount)}
                </div>
              </div>

              <div className="flex  items-center flex-row gap-20 status justify-center xl:w-2/3 sm:w-full">
                <div className="flex flex-row-reverse">
                  <span className="block w-7 h-2.5 bg-violet-500 rounded-tl-xl rounded-bl-xl"></span>
                  <span className="block w-7 h-2.5 bg-purple-500 "></span>
                  <span className="block w-7 h-2.5 bg-cyan-300 "></span>
                  <span className="block w-7 h-2.5 bg-pink-400 rounded-tr-xl rounded-br-xl"></span>
                </div>
                <div className="flex justify-center items-center gap-2">
                  <div className="text-base text-gray-400 mb-1">میانگین :‌</div>
                  <div className="font-bold">
                    {formatNumber(((stats.averageScore ?? 0) as number) ?? 0)}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Project Details Dialog */}
      <Dialog open={detailsDialogOpen} onOpenChange={setDetailsDialogOpen}>
        <DialogContent className="bg-[linear-gradient(to_bottom_left,#464861,50%,#111628)] max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-white mr-4 border-b-2 border-gray-600 pb-4 font-persian font-semibold text-sm text-right">
              شرح پروژه
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 flex justify-between text-right p-6">
            {/* Project Description */}
            <div className="flex-[4] border-l-2 border-gray-600">
              <h2 className="font-bold text-base">
                {selectedProjectDetails?.title}
              </h2>
              <p className="text-white font-normal text-base font-persian px-2 mt-2">
                {selectedProjectDetails?.project_description || "-"}
              </p>
            </div>

            {/* Project Details */}
            <div className="flex flex-[3] gap-2 flex-col px-4">
              <div className="font-bold text-right ">جزئیات پروژه</div>

              <div className="flex items-center justify-between">
                <h4 className="font-light text-sm text-white font-persian mb-2 flex items-center gap-1">
                  <Building2 className="h-4 text-green-500 text-sm font-light" />
                  زمان شروع:
                </h4>
                <span className="text-white font-normal text-base font-persian">
                  {selectedProjectDetails?.start_date
                    ? moment(
                        selectedProjectDetails?.start_date,
                        "YYYY-MM-DD"
                      ).format("YYYY/MM/DD")
                    : "-"}
                </span>
              </div>

              <div className="flex items-center justify-between">
                <h4 className="font-light text-sm text-white font-persian mb-2 flex items-center gap-1">
                  <PickaxeIcon className="h-4 text-green-500 text-sm font-light" />
                  زمان پایان:
                </h4>
                <span className="text-white font-normal text-base font-persian">
                  {selectedProjectDetails?.done_date
                    ? moment(
                        selectedProjectDetails?.done_date,
                        "YYYY-MM-DD"
                      ).format("YYYY/MM/DD")
                    : "-"}
                </span>
              </div>

              <div className="flex items-center justify-between">
                <h4 className="font-light text-sm text-white font-persian mb-2 flex items-center gap-1">
                  <UsersIcon className="h-4 text-green-500 text-sm font-light" />
                  هزینه برآورد شده:
                </h4>
                <span className="text-white font-normal text-base font-persian">
                  {selectedProjectDetails?.approved_budget
                    ? formatNumber(
                        Number(
                          selectedProjectDetails.approved_budget.replaceAll(
                            ",",
                            ""
                          )
                        )
                      )
                    : "-"}
                </span>
              </div>
              <div className="flex items-center justify-between">
                <h4 className="font-light text-sm text-white font-persian mb-2 flex items-center gap-1">
                  <UserIcon className="h-4 text-green-500 text-sm font-light" />
                  نفر مرتبط:
                </h4>
                <span className="text-white font-normal text-base font-persian">
                  {selectedProjectDetails?.observer || "-"}
                </span>
              </div>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </DashboardLayout>
  );
}
