import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  Building2,
  Target,
  TrendingUp,
  Users,
  ArrowRight,
  Star,
  Calendar,
  ArrowLeft,
  PlusIcon,
} from "lucide-react";
import { motion } from "framer-motion";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useSubPlans } from "@/performance-management/hooks/usePlans";
import { Button } from "@/shared/common/ui/button";
import { Skeleton } from "@/shared/common/ui/skeleton";
import { SectorList } from "@/performance-management/types/planTypes";
import { EPositionTypeKey } from "@/shared/dto/user/meDto";
import { useTranslation } from "react-i18next";

interface SubPlanListViewProps {
  positionType: EPositionTypeKey;
}

export const SubPlanListView: React.FC<SubPlanListViewProps> = ({
  positionType,
}) => {
  const navigate = useNavigate();
  const { yearId, planId } = useParams<{ yearId: string; planId: string }>();
  const localizedName = useLocalizedName();
  const { t } = useTranslation();

  const POSITION_TYPE_LABELS = {
    [EPositionTypeKey.DEPUTY]: {
      singular: t("subPlanListView.department"),
      plural: t("subPlanListView.departments"),
      title: t("subPlanListView.departmentOverview"),
      description: t("subPlanListView.departmentDescription"),
    },
    [EPositionTypeKey.DIRECTOR]: {
      singular: t("subPlanListView.director"),
      plural: t("subPlanListView.directors"),
      title: t("subPlanListView.directorOverview"),
      description: t("subPlanListView.directorDescription"),
    },
    [EPositionTypeKey.TEAM_LEADER]: {
      singular: t("subPlanListView.teamLeader"),
      plural: t("subPlanListView.teamLeaders"),
      title: t("subPlanListView.teamLeaderOverview"),
      description: t("subPlanListView.teamLeaderDescription"),
    },
    [EPositionTypeKey.EMPLOYEE]: {
      singular: t("subPlanListView.employee"),
      plural: t("subPlanListView.employees"),
      title: t("subPlanListView.employeeOverview"),
      description: t("subPlanListView.employeeDescription"),
    },
  } as const;

  const { data, isLoading, error } = useSubPlans(planId || "");
  const items: SectorList[] = data?.data?.items || [];

  const labels =
    POSITION_TYPE_LABELS[positionType as keyof typeof POSITION_TYPE_LABELS] ||
    POSITION_TYPE_LABELS[EPositionTypeKey.DEPUTY];

  const handleItemClick = (positionId: string, planId: string) => {
    if (yearId) {
      // Navigate to plans table for this sub-plan
      navigate(
        `/performance-management/${yearId}/plans-table/${positionId}/${planId}`
      );
    }
  };

  const handleCreateSubPlan = (item: SectorList) => {
    if (yearId && planId) {
      // Navigate to create plan with both positionId and parentPlanId
      navigate(
        `/performance-management/${yearId}/plans/new/${item.position_id}?parentPlanId=${planId}`
      );
    }
  };

  const getSectorColor = (index: number) => {
    const colors = [
      "from-blue-500 to-cyan-500",
      "from-purple-500 to-pink-500",
      "from-green-500 to-emerald-500",
      "from-orange-500 to-red-500",
      "from-indigo-500 to-blue-500",
      "from-teal-500 to-green-500",
    ];
    return colors[index % colors.length];
  };

  const getRankBadge = (rank: number) => {
    if (rank === 1)
      return "bg-gradient-to-r from-yellow-400 to-amber-500 text-white";
    if (rank === 2)
      return "bg-gradient-to-r from-gray-400 to-gray-500 text-white";
    if (rank === 3)
      return "bg-gradient-to-r from-amber-600 to-orange-500 text-white";
    return "bg-gradient-to-r from-slate-400 to-slate-500 text-white";
  };

  const getPerformanceColor = (weight: number) => {
    if (weight >= 90) return "text-green-500";
    if (weight >= 75) return "text-blue-500";
    if (weight >= 60) return "text-yellow-500";
    return "text-red-500";
  };

  if (isLoading) {
    return (
      <div className="p-6 space-y-6">
        <Skeleton className="h-64 w-full rounded-lg" />
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <Skeleton className="h-40 w-full rounded-lg" />
          <Skeleton className="h-40 w-full rounded-lg" />
          <Skeleton className="h-40 w-full rounded-lg" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="p-6">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
          <h3 className="text-red-800 dark:text-red-200 font-semibold mb-2">
            {t("subPlanListView.errorLoading")} {labels.plural}
          </h3>
          <p className="text-red-600 dark:text-red-400">
            {error instanceof Error
              ? error.message
              : `${t(
                  "subPlanListView.failedToLoad"
                )} ${labels.plural.toLowerCase()}`}
          </p>
          <Button
            variant="outline"
            onClick={() => navigate(-1)}
            className="mt-4 border-red-200 text-red-600 hover:bg-red-100"
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t("subPlanListView.goBack")}
          </Button>
        </div>
      </div>
    );
  }

  if (!items || items.length === 0) {
    return (
      <div className="p-6">
        <Button variant="outline" onClick={() => navigate(-1)} className="mb-6">
          <ArrowLeft className="mr-2 h-4 w-4" />
          {t("subPlanListView.back")}
        </Button>
        <div className="min-h-[400px] flex items-center justify-center bg-gradient-to-br from-slate-50 to-blue-50 rounded-2xl">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center"
          >
            <div className="w-20 h-20 bg-white/80 backdrop-blur-sm rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg border border-white/20">
              <Building2 className="h-10 w-10 text-gray-400" />
            </div>
            <h3 className="text-xl font-semibold text-gray-700 mb-2">
              {t("subPlanListView.noAvailable", { type: labels.plural })}
            </h3>
            <p className="text-gray-500 max-w-sm">
              {t("subPlanListView.noSubPlansToDisplay", {
                type: labels.plural.toLowerCase(),
              })}
            </p>
          </motion.div>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4"
      >
        <div>
          <div className="flex items-center gap-2 mb-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate(-1)}
              className="text-gray-500 hover:text-gray-700 -ml-2"
            >
              <ArrowLeft className="h-4 w-4 mr-1" />
              {t("subPlanListView.back")}
            </Button>
          </div>
          <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">
            {labels.title}
          </h1>
          <p className="text-gray-600 mt-2">{labels.description}</p>
        </div>

        <div className="flex items-center gap-3">
          <div className="flex items-center gap-3 bg-white/80 backdrop-blur-sm rounded-2xl px-4 py-2 shadow-sm border border-gray-200">
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
            <span className="text-sm font-medium text-gray-700">
              {items.length}{" "}
              {items.length === 1 ? labels.singular : labels.plural}{" "}
              {t("subPlanListView.active")}
            </span>
          </div>
        </div>
      </motion.div>

      {/* Stats Summary */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.1 }}
        className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8"
      >
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-gray-200/50">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-600 text-sm font-medium">
                {t("subPlanListView.totalPlans")}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {items.reduce(
                  (sum: number, item: SectorList) =>
                    sum + (Number(item.no_of_plans) || 0),
                  0
                )}
              </p>
            </div>
            <div className="w-12 h-12 bg-blue-500/10 rounded-2xl flex items-center justify-center">
              <Target className="h-6 w-6 text-blue-500" />
            </div>
          </div>
        </div>

        <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-gray-200/50">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-600 text-sm font-medium">
                {t("subPlanListView.avgWeight")}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {items.length > 0
                  ? Math.round(
                      items.reduce(
                        (sum: number, item: SectorList) =>
                          sum + (Number(item.total_weight) || 0),
                        0
                      ) / items.length
                    )
                  : 0}
                %
              </p>
            </div>
            <div className="w-12 h-12 bg-green-500/10 rounded-2xl flex items-center justify-center">
              <TrendingUp className="h-6 w-6 text-green-500" />
            </div>
          </div>
        </div>

        <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 shadow-lg border border-gray-200/50">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-gray-600 text-sm font-medium">
                {t("subPlanListView.active")} {labels.plural}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {
                  items.filter((s: SectorList) => Number(s.no_of_plans) > 0)
                    .length
                }
              </p>
            </div>
            <div className="w-12 h-12 bg-purple-500/10 rounded-2xl flex items-center justify-center">
              <Users className="h-6 w-6 text-purple-500" />
            </div>
          </div>
        </div>
      </motion.div>

      {/* Items Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        {items.map((item: SectorList, index: number) => (
          <motion.div
            key={item.position_id}
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: index * 0.1 }}
            className="group bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg hover:shadow-2xl transform hover:-translate-y-2 transition-all duration-300 border border-gray-200/50 hover:border-purple-300 overflow-hidden"
          >
            {/* Header with Gradient */}
            <div
              className={`bg-gradient-to-r ${getSectorColor(
                index
              )} p-6 relative overflow-hidden`}
            >
              <div className="absolute top-4 right-4">
                <div
                  className={`px-3 py-1 rounded-full text-xs font-bold ${getRankBadge(
                    item.position_rank
                  )} shadow-lg`}
                >
                  #{item.position_rank}
                </div>
              </div>

              <div className="flex items-center justify-between mb-4">
                <div className="w-12 h-12 bg-white/20 rounded-2xl flex items-center justify-center backdrop-blur-sm">
                  <Building2 className="h-6 w-6 text-white" />
                </div>
                <motion.div
                  whileHover={{ x: 5 }}
                  className="opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                >
                  <ArrowRight className="h-5 w-5 text-white/80" />
                </motion.div>
              </div>

              <h3 className="text-xl font-bold text-white line-clamp-2 leading-tight">
                {localizedName(item.position_name)}
              </h3>
            </div>

            {/* Content */}
            <div className="p-6 space-y-4">
              {/* Plans Count */}
              <div className="flex items-center justify-between p-3 bg-blue-50 rounded-xl">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-blue-500/10 rounded-lg flex items-center justify-center">
                    <Target className="h-5 w-5 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-600">
                      {t("subPlanListView.totalPlans")}
                    </p>
                    <p className="text-lg font-bold text-gray-900">
                      {item.no_of_plans || 0}
                    </p>
                  </div>
                </div>
                {Number(item.no_of_plans) > 0 && (
                  <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                )}
              </div>

              {/* Total Weight */}
              {item.total_weight !== null && (
                <div className="flex items-center justify-between p-3 bg-green-50 rounded-xl">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-green-500/10 rounded-lg flex items-center justify-center">
                      <TrendingUp className="h-5 w-5 text-primary-600" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-600">
                        {t("subPlanListView.avgWeight")}
                      </p>
                      <p
                        className={`text-lg font-bold ${getPerformanceColor(
                          item.total_weight
                        )}`}
                      >
                        {item.total_weight}%
                      </p>
                    </div>
                  </div>

                  {/* Performance Indicator */}
                  <div className="flex items-center gap-1">
                    {[...Array(5)].map((_, i) => (
                      <Star
                        key={i}
                        className={`h-4 w-4 ${
                          i < Math.floor((item.total_weight || 0) / 20)
                            ? "text-yellow-400 fill-current"
                            : "text-gray-300"
                        }`}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex items-center gap-2 pt-4">
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleItemClick(item.position_id, planId as string);
                  }}
                  variant="outline"
                  size="sm"
                  className="flex-1 border-blue-200 text-blue-600 hover:bg-blue-50"
                >
                  {t("subPlanListView.viewPlans")}
                </Button>
                <Button
                  onClick={(e) => {
                    e.stopPropagation();
                    handleCreateSubPlan(item);
                  }}
                  size="sm"
                  className="flex-1 bg-gradient-to-r from-purple-500 to-violet-600 hover:from-purple-600 hover:to-violet-700 text-white"
                >
                  <PlusIcon className="h-4 w-4 mr-1" />
                  {t("subPlanListView.createPlan")}
                </Button>
              </div>

              {/* Additional Info */}
              <div className="flex items-center justify-between text-sm text-gray-500 pt-2">
                <div className="flex items-center gap-1">
                  <Calendar className="h-4 w-4" />
                  <span>{t("subPlanListView.active")}</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span className="font-medium">
                    {t("subPlanListView.online")}
                  </span>
                </div>
              </div>
            </div>

            {/* Hover Effect Overlay */}
            <div className="absolute inset-0 bg-gradient-to-br from-purple-500/5 to-blue-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-2xl pointer-events-none"></div>
          </motion.div>
        ))}
      </div>
    </div>
  );
};
