import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import {
  Building2,
  Target,
  TrendingUp,
  Users,
  ArrowRight,
  Star,
  Calendar,
} from "lucide-react";
import { motion } from "framer-motion";
import { SectorList } from "@/performance-management/types/planTypes";
import { useLocalizedName } from "@/shared/common/localizedName";
import { usePlanYears } from "@/performance-management/hooks/usePlanYear";
import { useAuth } from "@/shared/context/AuthContext";
import { getUserPositionType } from "@/performance-management/utils/positionTypeUtils";

interface SectorListViewProps {
  sectors: SectorList[];
}

export const SectorListView: React.FC<SectorListViewProps> = ({ sectors }) => {
  const navigate = useNavigate();
  const { yearId } = useParams<{ yearId: string }>();
  const localizedName = useLocalizedName();
  const { t } = useTranslation();

  // const { data: planYear } = usePlanYears(organizationId);
  const handleSectorClick = (positionId: string) => {
    if (yearId) {
      navigate(`/performance-management/${yearId}/plans-table/${positionId}`);
    }
  };

  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 (!sectors || sectors.length === 0) {
    return (
      <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("sectorListView.noSectorsAvailable", "No Sectors Available")}
          </h3>
          <p className="text-gray-500 max-w-sm">
            {t(
              "sectorListView.noSectorsMessage",
              "There are no sectors to display at this time. Sectors will appear here once they are added to the system."
            )}
          </p>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="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>
          <h1 className="text-3xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">
            {t("sectorListView.title", "Sector Overview")}
          </h1>
          <p className="text-gray-600 mt-2">
            {t(
              "sectorListView.description",
              "Manage and monitor performance across all sectors"
            )}
          </p>
        </div>

        <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">
            {sectors.length}{" "}
            {sectors.length === 1
              ? t("sectorListView.sector", "Sector")
              : t("sectorListView.sectors", "Sectors")}{" "}
            {t("sectorListView.active", "Active")}
          </span>
        </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("sectorListView.totalPlans", "Total Plans")}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {sectors.reduce(
                  (sum, sector) => sum + Number(sector.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("sectorListView.avgWeight", "Avg. Weight")}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {Math.round(
                  sectors.reduce(
                    (sum, sector) => sum + Number(sector.total_weight || 0),
                    0
                  ) / sectors.length
                )}
                %
              </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("sectorListView.activeSectors", "Active Sectors")}
              </p>
              <p className="text-3xl font-bold text-gray-900">
                {sectors.filter((s) => 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>

      {/* Sectors Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
        {sectors.map((sector, index) => (
          <motion.div
            key={sector.position_id}
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ delay: index * 0.1 }}
            onClick={() => handleSectorClick(sector.position_id)}
            className="group bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg hover:shadow-2xl cursor-pointer 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(
                    sector.position_rank
                  )} shadow-lg`}
                >
                  #{sector.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(sector.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("sectorListView.plans", "Plans")}
                    </p>
                    <p className="text-lg font-bold text-gray-900">
                      {sector.no_of_plans || 0}
                    </p>
                  </div>
                </div>
                {sector.no_of_plans > 0 && (
                  <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                )}
              </div>

              {/* Total Weight */}
              {sector.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("sectorListView.weight", "Weight")}
                      </p>
                      <p
                        className={`text-lg font-bold ${getPerformanceColor(
                          sector.total_weight
                        )}`}
                      >
                        {sector.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(sector.total_weight! / 20)
                            ? "text-yellow-400 fill-current"
                            : "text-gray-300"
                        }`}
                      />
                    ))}
                  </div>
                </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("sectorListView.active", "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("sectorListView.online", "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>

      {/* Footer Summary */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5 }}
        className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-2xl p-6 border border-blue-200/50 mt-8"
      >
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold text-gray-800">
              {t("sectorListView.performanceSummary", "Performance Summary")}
            </h3>
            <p className="text-gray-600 text-sm">
              {t(
                "sectorListView.performanceSummaryDescription",
                "All sectors are actively monitored and updated in real-time"
              )}
            </p>
          </div>
          <div className="flex items-center gap-4 text-sm">
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-green-500 rounded-full"></div>
              <span className="text-gray-700">
                {t("sectorListView.onTrack", "On Track")}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
              <span className="text-gray-700">
                {t("sectorListView.needsAttention", "Needs Attention")}
              </span>
            </div>
            <div className="flex items-center gap-2">
              <div className="w-3 h-3 bg-red-500 rounded-full"></div>
              <span className="text-gray-700">
                {t("sectorListView.atRisk", "At Risk")}
              </span>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
};
