import React, { useMemo } from "react";
import { Card, CardContent } from "@/shared/common/ui/card";
import {
  Clock,
  Users,
  CheckCircle2,
  AlertCircle,
  LucideIcon,
  TrendingUp,
  RefreshCw,
  CircleX,
  MessageSquareReply,
} from "lucide-react";
import { AssignmentApiResponse } from "@/record-management/dto/AssignementStep";
import { useTranslation } from "react-i18next";
import { cn } from "@/shared/lib/utils";
import { useReport } from "../../hooks/useReport";

interface RecordAssignmentStatsProps {
  recordId: string;
}

const RecordAssignmentStats: React.FC<RecordAssignmentStatsProps> = ({
  recordId,
}) => {
  const { t } = useTranslation();
  const { report } = useReport(recordId);
  const stats = useMemo(() => {
    const reassignedSteps =
      Number(report.find((s) => s.status === "re_assigned")?.count) || 0;

    const acceptedSteps =
      Number(report.find((s) => s.status === "accepted")?.count) || 0;
    const pendingSteps =
      Number(report.find((s) => s.status === "draft")?.count) || 0;
    const repliedSteps =
      Number(report.find((s) => s.status === "replied")?.count) || 0;
    const rejectedSteps =
      Number(report.find((s) => s.status === "rejected")?.count) || 0;

    const totalAllocations =
      reassignedSteps +
      acceptedSteps +
      pendingSteps +
      rejectedSteps +
      repliedSteps;
    return {
      totalAllocations,
      reassignedAssignments: reassignedSteps,
      acceptedAssignments: acceptedSteps,
      pendingAssignments: pendingSteps,
      rejectedAssigments: rejectedSteps,
      repliedAssigments: repliedSteps,
      completionRate:
        totalAllocations > 0
          ? Math.round(
              ((acceptedSteps +
                rejectedSteps +
                reassignedSteps +
                repliedSteps) /
                totalAllocations) *
                100,
            )
          : 0,
      avgResponseTime: "N/A",
    };
  }, [report]);

  interface StatItem {
    label: string;
    value: number | string;
    icon: LucideIcon;
    iconColor: string;
    bgColor: string;
    textColor?: string;
    trend?: number;
    description?: string;
  }

  const statsData: StatItem[] = [
    {
      label: t("statusBar.totalAllocations"),
      value: stats.totalAllocations,
      icon: Users,
      iconColor: "text-blue-600",
      bgColor: "bg-blue-50",
      textColor: "text-blue-700",
      description: t("msg.totalAllocations"),
    },
    {
      label: t("statusBar.draft"),
      value: stats.pendingAssignments,
      icon: AlertCircle,
      iconColor: "text-amber-600",
      bgColor: "bg-amber-50",
      textColor: "text-amber-700",
      description: t("msg.draft"),
    },
    {
      label: t("statusBar.Reassigned"),
      value: stats.reassignedAssignments,
      icon: RefreshCw,
      iconColor: "text-purple-600",
      bgColor: "bg-purple-50",
      textColor: "text-purple-700",
      description: t("msg.reassigned"),
    },
    {
      label: t("statusBar.Accepted"),
      value: stats.acceptedAssignments,
      icon: CheckCircle2,
      iconColor: "text-green-600",
      bgColor: "bg-green-50",
      textColor: "text-green-700",
      description: t("msg.accepted"),
    },
    {
      label: t("statusBar.replied"),
      value: stats.repliedAssigments,
      icon: MessageSquareReply,
      iconColor: "text-green-600",
      bgColor: "bg-green-50",
      textColor: "text-green-700",
      description: t("msg.replied"),
    },
    {
      label: t("statusBar.Rejected"),
      value: stats.rejectedAssigments,
      icon: CircleX,
      iconColor: "text-red-600",
      bgColor: "bg-red-50",
      textColor: "text-red-700",
      description: t("msg.rejected"),
    },
    {
      label: t("statusBar.completionRate"),
      value: `${stats.completionRate}%`,
      icon: TrendingUp,
      iconColor: "text-green-800",
      bgColor: "bg-green-50",
      textColor: "text-green-900",
      description: t("msg.completionRate"),
    },
  ];

  return (
    <Card className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm hover:shadow-md transition-shadow duration-200">
      <CardContent className="p-6 overflow-x-auto md:overflow-visible dark:bg-gray-800">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h3 className="text-xl font-semibold text-gray-900 dark:text-white">
              {t("statusBar.assignmentStatistics")}
            </h3>
          </div>
          <div className="hidden sm:flex items-center space-x-2 px-3 py-1.5 bg-gray-50 dark:bg-gray-700 rounded-lg">
            <Clock className="h-4 w-4 text-gray-400 dark:text-gray-500" />
            <span className="text-sm text-gray-600 dark:text-gray-300">
              {t("dashboard.lastUpdated")}:{" "}
              {new Date().toLocaleString(undefined, {
                dateStyle: "medium",
                timeStyle: "short",
              })}
            </span>
          </div>
        </div>

        {/* Grid layout for better responsiveness */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {statsData.map((stat, idx) => (
            <div
              key={idx}
              className={cn(
                "group relative p-4 rounded-lg border border-gray-100 dark:border-gray-700 transition-all duration-200",
                "hover:border-gray-200 dark:hover:border-gray-600 hover:shadow-md bg-white dark:bg-gray-800",
              )}
            >
              <div className="flex items-start justify-between">
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-1 truncate">
                    {stat.label}
                  </p>
                  <p
                    className={cn(
                      "text-2xl font-bold truncate",
                      stat.textColor,
                      "dark:text-gray-200",
                    )}
                  >
                    {stat.value}
                  </p>
                  {stat.description && (
                    <p className="text-xs text-gray-400 dark:text-gray-500 mt-2 line-clamp-2">
                      {stat.description}
                    </p>
                  )}
                </div>
                <div
                  className={cn(
                    "p-2 rounded-lg transition-colors duration-200",
                    stat.bgColor,
                    "dark:bg-opacity-20",
                    "group-hover:bg-opacity-80",
                  )}
                >
                  <stat.icon
                    className={cn("h-5 w-5", stat.iconColor, "dark:opacity-80")}
                  />
                </div>
              </div>

              {/* Progress bar for completion rate */}
              {stat.label === t("statusBar.completionRate") ? (
                <div className="mt-3">
                  <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5">
                    <div
                      className="bg-green-500 dark:bg-green-400 h-1.5 rounded-full transition-all duration-500"
                      style={{ width: `${stats.completionRate}%` }}
                    />
                  </div>
                </div>
              ) : (
                <div className="mt-3">
                  <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-1.5"></div>
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Summary section */}
        <div className="mt-6 pt-4 border-t border-gray-100 dark:border-gray-700">
          <div className="flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center space-x-4 text-sm text-gray-600 dark:text-gray-400">
              <div className="flex items-center space-x-1">
                <div className="w-2 h-2 bg-green-500 dark:bg-green-400 rounded-full"></div>
                <span>
                  {t("assignment.onTrack")}:{" "}
                  {stats.acceptedAssignments +
                    stats.repliedAssigments +
                    stats.reassignedAssignments +
                    stats.rejectedAssigments}
                </span>
              </div>
              <div className="flex items-center space-x-1">
                <div className="w-2 h-2 bg-amber-500 dark:bg-amber-400 rounded-full"></div>
                <span>
                  {t("assignment.attentionNeeded")}: {stats.pendingAssignments}
                </span>
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default RecordAssignmentStats;
