"use client";

import { useState, useEffect, useRef } from "react";
import { motion } from "motion/react";
import { Button } from "@/components/ui/button";
import { UserReportCard } from "./user-report-card";
import { AlertCircle } from "lucide-react";
import { DetailPanelSkeleton } from "@/components/ui/loading-skeletons";
import { staggerContainer, staggerItem } from "@/lib/motion";
import { api } from "@/lib/store/api";
import { apiCall, apiErrorMessage } from "@/lib/store/api-call";

interface UserReportCardWrapperProps {
  userId: string;
  userName: string;
  dateFrom?: string;
  dateTo?: string;
  /** Prefetched report-card payload (e.g. during evaluation splash) */
  initialData?: any | null;
  initialError?: string | null;
}

function MetricCell({
  label,
  value,
  active,
}: {
  label: string;
  value: string;
  active: boolean;
}) {
  return (
    <div className="px-5 py-4">
      <div className="text-xs text-muted-foreground mb-1">{label}</div>
      <div
        className={
          active
            ? "text-sm font-semibold tabular-nums text-emerald-700 dark:text-emerald-300"
            : "text-sm tabular-nums text-muted-foreground"
        }
      >
        {value}
      </div>
    </div>
  );
}

export function UserReportCardWrapper({
  userId,
  userName,
  dateFrom,
  dateTo,
  initialData = null,
  initialError = null,
}: UserReportCardWrapperProps) {
  const queryKey = `${userId}|${dateFrom ?? ""}|${dateTo ?? ""}`;
  const [loading, setLoading] = useState(!initialData && !initialError);
  const [error, setError] = useState<string | null>(initialError);
  const [data, setData] = useState<any>(initialData);
  const loadedKeyRef = useRef<string | null>(
    initialData || initialError ? queryKey : null,
  );

  const fetchReportCardData = async (force = false) => {
    try {
      setLoading(true);
      setError(null);
      const reportData = await apiCall(
        api.endpoints.getReportCard.initiate(
          { userId, startDate: dateFrom, endDate: dateTo },
          { forceRefetch: force },
        ),
      );
      setData(reportData);
      loadedKeyRef.current = queryKey;
    } catch (err) {
      console.error("Error fetching report card data:", err);
      setError(apiErrorMessage(err, "An error occurred"));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (loadedKeyRef.current === queryKey && (data || error)) {
      setLoading(false);
      return;
    }
    // Always hit the server: KPI edits on other tabs may have changed the scores.
    fetchReportCardData(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userId, dateFrom, dateTo]);

  if (loading) {
    return <DetailPanelSkeleton />;
  }

  if (error) {
    return (
      <div className="rounded-xl border border-border bg-card p-8">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">
            Error Loading Report Card
          </h3>
          <p className="text-muted-foreground mb-4">{error}</p>
          <Button onClick={() => fetchReportCardData(true)}>Try Again</Button>
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="rounded-xl border border-border bg-card p-8">
        <div className="text-center">
          <h3 className="text-lg font-semibold text-foreground mb-2">
            No Data Available
          </h3>
          <p className="text-muted-foreground">
            Report card data is not available for this user.
          </p>
        </div>
      </div>
    );
  }

  const availability = data.summary.dataAvailability;

  return (
    <motion.div
      className="space-y-6"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      <motion.div
        variants={staggerItem}
        className="rounded-xl border border-border overflow-hidden bg-card"
      >
        <div className="px-5 py-4 border-b border-border">
          <h3 className="text-lg font-semibold tracking-tight text-foreground">
            Performance Report Card
          </h3>
          <p className="text-sm text-muted-foreground">
            Comprehensive evaluation for {userName}
          </p>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 divide-x divide-y lg:divide-y-0 divide-border">
          <MetricCell
            label="Departmental KPIs"
            value={`${data.summary.totalMonthlyRecords} records`}
            active={availability.hasMonthlyPerformance}
          />
          <MetricCell
            label="Personnel KPIs"
            value={`${data.summary.totalBiannualRecords} records`}
            active={availability.hasBiannualPerformance}
          />
          <MetricCell
            label="Attendance"
            value={`${data.summary.totalAttendanceRecords} months`}
            active={availability.hasAttendance}
          />
          <MetricCell
            label="Work Summary"
            value={`${data.summary.totalLoggedHours.toFixed(2)}h logged`}
            active={availability.hasLoggedHours}
          />
        </div>
      </motion.div>

      <UserReportCard
        user={data.user}
        monthlyPerformance={data.monthlyPerformance || []}
        sqaMonthlyPerformance={data.sqaMonthlyPerformance || []}
        unitLeadMonthlyPerformance={data.unitLeadMonthlyPerformance || []}
        designMonthlyPerformance={data.designMonthlyPerformance || []}
        itMonthlyPerformance={data.itMonthlyPerformance || []}
        marketingMonthlyPerformance={data.marketingMonthlyPerformance || []}
        seoMonthlyPerformance={data.seoMonthlyPerformance || []}
        pmoMonthlyPerformance={data.pmoMonthlyPerformance || []}
        biannualPerformance={data.biannualPerformance || []}
        designBiannualPerformance={data.designBiannualPerformance || []}
        marketingBiannualPerformance={data.marketingBiannualPerformance || []}
        seoBiannualPerformance={data.seoBiannualPerformance || []}
        monthlyAttendance={data.monthlyAttendance || []}
        loggedHours={data.loggedHours || []}
        loggedHoursSummary={data.loggedHoursSummary || null}
        itWorkHistory={data.itWorkHistory || []}
        isUserSqa={data.isUserSqa}
        isUserUnitLead={data.isUserUnitLead}
        isUserDesign={data.isUserDesign}
        isMarketingUser={data.isMarketingUser}
        isSeoUser={data.isSeoUser}
        userPerformanceType={data.userPerformanceType}
        designPerformanceType={data.designPerformanceType}
      />
    </motion.div>
  );
}
