"use client";

/**
 * Project Header Banner Component
 *
 * Displays project information with:
 * - Project title and description
 * - Animated overall progress percentage
 * - Animated circular progress indicator
 * - Decorative background pattern matching Figma design
 * - Fully responsive for mobile and desktop
 * - Dynamic colors from dashboard settings
 */

import { useSettingsContext } from "@/contexts/settings-context";
import { useFormattedDate } from "@/hooks/use-formatted-date";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useMemo, useRef, useState } from "react";

interface ProjectHeaderBannerProps {
  projectName: string;
  name_translations?: {
    ar: string;
    en: string;
  };
  description?: string;
  description_translations?: {
    ar: string;
    en: string;
  };
  progressPercentage: number;
  endDate?: string;
  daysRemaining?: number;
}

function formatDaysRemainingLabel({
  daysRemaining,
  t,
}: {
  daysRemaining: number;
  t: ReturnType<typeof useTranslations<"dashboard">>;
}) {
  const daysRemainingText = t("daysRemaining", { days: daysRemaining });

  const daysPerYear = 365;
  const windowDays = 7;
  const years = Math.round(daysRemaining / daysPerYear);

  if (
    years < 1 ||
    Math.abs(daysRemaining - years * daysPerYear) > windowDays
  ) {
    return `(${daysRemainingText})`;
  }

  const yearsText = t("yearsCount", { count: years });
  return `${yearsText} (${daysRemainingText})`;
}

/**
 * Darken a color by a percentage
 * Supports hex colors
 */
function darkenColor(color: string, percent: number): string {
  // Handle hex colors
  if (color.startsWith("#")) {
    const hex = color.replace("#", "");
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);

    const newR = Math.max(0, Math.floor(r * (1 - percent / 100)));
    const newG = Math.max(0, Math.floor(g * (1 - percent / 100)));
    const newB = Math.max(0, Math.floor(b * (1 - percent / 100)));

    return `#${newR.toString(16).padStart(2, "0")}${newG.toString(16).padStart(2, "0")}${newB.toString(16).padStart(2, "0")}`;
  }

  // Handle oklch colors
  if (color.includes("oklch")) {
    const match = color.match(/oklch\(([\d.]+)\s+([\d.]+)\s+([\d.]+)\)/);
    if (match) {
      const lightness = parseFloat(match[1]);
      const chroma = parseFloat(match[2]);
      const hue = parseFloat(match[3]);

      // Reduce lightness to darken
      const newLightness = Math.max(0, lightness * (1 - percent / 100));

      return `oklch(${newLightness.toFixed(3)} ${chroma} ${hue})`;
    }
  }

  return color;
}

/**
 * Lighten a color by a percentage
 * Supports hex colors
 */
function lightenColor(color: string, percent: number): string {
  // Handle hex colors
  if (color.startsWith("#")) {
    const hex = color.replace("#", "");
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);

    const newR = Math.min(255, Math.floor(r + (255 - r) * (percent / 100)));
    const newG = Math.min(255, Math.floor(g + (255 - g) * (percent / 100)));
    const newB = Math.min(255, Math.floor(b + (255 - b) * (percent / 100)));

    return `#${newR.toString(16).padStart(2, "0")}${newG.toString(16).padStart(2, "0")}${newB.toString(16).padStart(2, "0")}`;
  }

  // Handle oklch colors
  if (color.includes("oklch")) {
    const match = color.match(/oklch\(([\d.]+)\s+([\d.]+)\s+([\d.]+)\)/);
    if (match) {
      const lightness = parseFloat(match[1]);
      const chroma = parseFloat(match[2]);
      const hue = parseFloat(match[3]);

      // Increase lightness to lighten
      const newLightness = Math.min(1, lightness + (1 - lightness) * (percent / 100));

      return `oklch(${newLightness.toFixed(3)} ${chroma} ${hue})`;
    }
  }

  return color;
}

export function ProjectHeaderBanner({
  projectName,
  name_translations,
  description,
  description_translations,
  progressPercentage,
  endDate,
  daysRemaining,
}: ProjectHeaderBannerProps) {
  const t = useTranslations("dashboard");
  const locale = useLocale() as "ar" | "en";
  const { formatDate } = useFormattedDate();
  const { primaryColor, secondaryColor } = useSettingsContext();

  const displayProjectName =
    name_translations?.[locale] || name_translations?.ar || projectName;
  const displayDescription =
    description_translations?.[locale] ||
    description_translations?.ar ||
    description;

  const daysRemainingLabel = useMemo(() => {
    if (daysRemaining == null || daysRemaining <= 0) {
      return null;
    }

    return formatDaysRemainingLabel({ daysRemaining, t });
  }, [daysRemaining, t]);

  const [animatedProgress, setAnimatedProgress] = useState(0);
  const [barProgress, setBarProgress] = useState(0);
  const animationFrameRef = useRef<number | null>(null);
  const barAnimationFrameRef = useRef<number | null>(null);
  const latestProgressRef = useRef(0);

  // Compute colors based on settings
  const colors = useMemo(() => {
    // Background: Use secondary color darkened, or fallback to dark green
    const bgColor = secondaryColor
      ? darkenColor(secondaryColor, 50)
      : "#003620";

    // Progress bar/indicator: Use primary color
    const progressColor = primaryColor || "#1b8354";

    // Lighter version of primary for progress bar background
    const progressBgColor = lightenColor(progressColor, 30);

    return {
      bgColor,
      progressColor,
      progressBgColor,
    };
  }, [primaryColor, secondaryColor]);

  // Animate progress on mount and when value changes
  useEffect(() => {
    const targetProgress = Math.min(Math.max(progressPercentage, 0), 100);
    const startProgress = latestProgressRef.current;
    const duration = 1400;

    if (animationFrameRef.current !== null) {
      cancelAnimationFrame(animationFrameRef.current);
    }
    if (barAnimationFrameRef.current !== null) {
      cancelAnimationFrame(barAnimationFrameRef.current);
    }

    barAnimationFrameRef.current = requestAnimationFrame(() => {
      setBarProgress(targetProgress);
      barAnimationFrameRef.current = null;
    });

    const startTime = performance.now();
    const easeOutCubic = (value: number) => 1 - Math.pow(1 - value, 3);

    const animate = (currentTime: number) => {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const easedProgress = easeOutCubic(progress);
      const nextValue =
        startProgress + (targetProgress - startProgress) * easedProgress;

      latestProgressRef.current = nextValue;
      setAnimatedProgress(nextValue);

      if (progress < 1) {
        animationFrameRef.current = requestAnimationFrame(animate);
        return;
      }

      latestProgressRef.current = targetProgress;
      setAnimatedProgress(targetProgress);
      animationFrameRef.current = null;
    };

    animationFrameRef.current = requestAnimationFrame(animate);

    return () => {
      if (animationFrameRef.current !== null) {
        cancelAnimationFrame(animationFrameRef.current);
        animationFrameRef.current = null;
      }
      if (barAnimationFrameRef.current !== null) {
        cancelAnimationFrame(barAnimationFrameRef.current);
        barAnimationFrameRef.current = null;
      }
    };
  }, [progressPercentage]);

  // Calculate circle properties (half circle - 180 degrees)
  // Desktop radius - exactly as Figma (278px diameter / 2 = 139px radius)
  const radius = 139;
  const circumference = Math.PI * radius;
  const strokeDashoffset =
    circumference - (animatedProgress / 100) * circumference;

  // Mobile radius (smaller)
  const mobileRadius = 80;
  const mobileCircumference = Math.PI * mobileRadius;
  const mobileStrokeDashoffset =
    mobileCircumference - (animatedProgress / 100) * mobileCircumference;

  const rotationAngle = (animatedProgress / 100) * 180; // Only 180 degrees

  return (
    <div
      className="relative overflow-hidden rounded-2xl sm:h-75"
      style={{ backgroundColor: colors.bgColor }}
    >
      {/* Decorative Background Pattern - Matching Figma exactly */}
      <div className="absolute inset-0 opacity-[0.06] pointer-events-none">
        {/* Grid pattern */}
        <div
          className="absolute inset-0"
          style={{
            backgroundImage: `
              repeating-linear-gradient(
                0deg,
                transparent,
                transparent 42px,
                rgba(255, 255, 255, 0.5) 42px,
                rgba(255, 255, 255, 0.5) 43px
              ),
              repeating-linear-gradient(
                90deg,
                transparent,
                transparent 42px,
                rgba(255, 255, 255, 0.5) 42px,
                rgba(255, 255, 255, 0.5) 43px
              )
            `,
          }}
        />
      </div>

      {/* Gradient overlay - matching Figma */}
      <div className="absolute top-0 left-0 w-full h-full opacity-20 pointer-events-none">
        <div className="absolute top-0 left-0 w-[916px] h-[322px] bg-gradient-to-br from-white/30 to-transparent rounded-full blur-3xl transform -translate-y-1/2 translate-x-[133px]" />
      </div>

      <div className="relative flex flex-col-reverse sm:h-full sm:flex-row items-center px-4 sm:px-8 py-6 sm:py-0 gap-5 sm:gap-0">
        {/* Project Info - Left Side on Desktop, Bottom on Mobile */}
        <div className="flex-1 flex flex-col items-center sm:items-start gap-3 sm:gap-6 min-w-0 w-full sm:w-auto sm:ms-8 lg:ms-16 sm:me-auto">
          {/* Content Container - 720px width on desktop as per Figma */}
          <div className="flex flex-col gap-3 sm:gap-6 w-full sm:max-w-[720px]">
            {/* Title and Description */}
            <div className="flex flex-col gap-2 sm:gap-4 w-full">
              <h2 className="text-center sm:text-start text-lg sm:text-[30px] font-medium text-white leading-tight sm:leading-[38px]">
                {displayProjectName}
              </h2>
              {displayDescription && (
                <p className="text-center sm:text-start text-xs sm:text-sm text-white/60 leading-relaxed sm:leading-[20px] max-w-full sm:max-w-[619px] line-clamp-3 sm:line-clamp-none">
                  {displayDescription}
                </p>
              )}
            </div>

            {/* Progress Bar - 320px width as per Figma */}
            <div className="flex flex-col gap-1 w-full sm:max-w-[320px]">
              <p className="text-center sm:text-start text-sm sm:text-base text-white">
                {t("projectProgress") || "تقدم المشروع"}
              </p>
              {/* Progress Bar matching Figma exactly */}
              <div className="bg-white/10 dark:bg-muted/50 rounded-lg overflow-hidden h-4">
                <div
                  className="rounded-lg h-full flex items-center px-2 transition-[width] duration-[1400ms] ease-[cubic-bezier(0.22,1,0.36,1)] will-change-[width]"
                  style={{
                    width: `${barProgress}%`,
                    backgroundColor: colors.progressColor,
                  }}
                >
                  <span className="text-xs text-white font-normal">
                    {Math.round(animatedProgress)}%
                  </span>
                </div>
              </div>
            </div>

            {/* Delivery Date */}
            {endDate && (
              <div className="flex flex-wrap items-center justify-center sm:justify-start gap-2 text-white/60">
                <svg
                  className="h-4 w-4 shrink-0"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect width="18" height="18" x="3" y="4" rx="2" ry="2" />
                  <line x1="16" x2="16" y1="2" y2="6" />
                  <line x1="8" x2="8" y1="2" y2="6" />
                  <line x1="3" x2="21" y1="10" y2="10" />
                </svg>
                <span className="text-center sm:text-start text-xs sm:text-sm">
                  {t("submissionDate")}:{" "}
                  <span className="text-white/80">
                    {formatDate(endDate)}
                  </span>
                  {daysRemainingLabel && (
                    <span className="ms-2 text-white/50">
                      {daysRemainingLabel}
                    </span>
                  )}
                </span>
              </div>
            )}
          </div>
        </div>

        {/* Circular Progress Indicator - Right Side on Desktop, Top on Mobile */}
        <div className="h-auto sm:absolute sm:end-8 lg:end-[122px] sm:top-1/2 sm:-translate-y-1/2 flex items-center justify-center pt-2 sm:pt-0">
          {/* Desktop Version - Hidden on Mobile */}
          <div className="hidden sm:block relative w-[278px] h-[139px]">
            {/* SVG Half-Circle Progress - Matching Figma exactly */}
            <svg
              className="absolute bottom-0 left-0 w-full h-full"
              viewBox="0 0 278 139"
              style={{ overflow: "visible" }}
            >
              {/* Background Arc */}
              <path
                d={`M 0 139 A ${radius} ${radius} 0 0 1 ${radius * 2} 139`}
                fill="none"
                stroke="currentColor"
                className="text-white/20"
                strokeWidth="12"
                strokeLinecap="round"
              />
              {/* Animated Progress Arc - Primary color from settings */}
              <path
                d={`M 0 139 A ${radius} ${radius} 0 0 1 ${radius * 2} 139`}
                fill="none"
                stroke={colors.progressColor}
                strokeWidth="12"
                strokeLinecap="round"
                strokeDasharray={circumference}
                strokeDashoffset={strokeDashoffset}
              />

              {/* Indicator Dot - Matching Figma */}
              <circle
                cx={
                  radius +
                  Math.cos(((180 - rotationAngle) * Math.PI) / 180) * radius
                }
                cy={
                  139 -
                  Math.sin(((180 - rotationAngle) * Math.PI) / 180) * radius
                }
                r="10"
                fill={colors.progressColor}
                stroke="white"
                strokeWidth="3"
              />
            </svg>

            {/* Animated Percentage Text - Centered as per Figma */}
            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/4">
              <p
                className="text-[56px] font-bold text-white tabular-nums leading-[84px] text-center"
                dir="ltr"
              >
                {Math.round(animatedProgress)}%
              </p>
            </div>
          </div>

          {/* Mobile Version - Smaller Circular Progress */}
          <div className="sm:hidden relative w-[260px] h-[150px]">
            <svg
              className="absolute bottom-0 left-0 w-full h-full"
              viewBox="0 0 190 110"
              style={{ overflow: "visible" }}
            >
              {/*
                Mobile arc geometry:
                - Radius: 80
                - Baseline Y: 100
                - Padding X: 15 (so the arc doesn't touch the edges)
              */}
              {/* Background Arc */}
              <path
                d={`M 15 100 A ${mobileRadius} ${mobileRadius} 0 0 1 ${15 + mobileRadius * 2} 100`}
                fill="none"
                stroke="currentColor"
                className="text-white/20"
                strokeWidth="10"
                strokeLinecap="round"
              />
              {/* Animated Progress Arc */}
              <path
                d={`M 15 100 A ${mobileRadius} ${mobileRadius} 0 0 1 ${15 + mobileRadius * 2} 100`}
                fill="none"
                stroke={colors.progressColor}
                strokeWidth="10"
                strokeLinecap="round"
                strokeDasharray={mobileCircumference}
                strokeDashoffset={mobileStrokeDashoffset}
              />

              {/* Indicator Dot */}
              <circle
                cx={
                  15 +
                  mobileRadius +
                  Math.cos(((180 - rotationAngle) * Math.PI) / 180) *
                  mobileRadius
                }
                cy={
                  100 -
                  Math.sin(((180 - rotationAngle) * Math.PI) / 180) *
                  mobileRadius
                }
                r="6"
                fill={colors.progressColor}
                stroke="white"
                strokeWidth="2.5"
              />
            </svg>

            {/* Animated Percentage Text - Centered in the arc */}
            <div className="absolute inset-0 flex items-center justify-center translate-y-3">
              <p
                className="text-[40px] font-bold text-white tabular-nums leading-none text-center"
                dir="ltr"
              >
                {Math.round(animatedProgress)}%
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
