import { useActionQuery } from "@agent-native/core/client/hooks";
import { useT } from "@agent-native/core/client/i18n";
import {
  IconTrendingUp,
  IconActivity,
  IconChartBar,
} from "@tabler/icons-react";
import { subDays } from "date-fns";
import type { CSSProperties } from "react";
import { useState, useEffect } from "react";
import { Link } from "react-router";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  Tooltip as ChartTooltip,
  ResponsiveContainer,
  AreaChart,
  Area,
} from "recharts";

import { QueryErrorState } from "@/components/QueryErrorState";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn, formatLocalDate } from "@/lib/utils";

function readActiveChart() {
  if (typeof window === "undefined") return "weight";
  try {
    return window.localStorage.getItem("hero_active_chart") || "weight";
  } catch {
    return "weight";
  }
}

function writeActiveChart(activeChart: string) {
  if (typeof window === "undefined") return;
  try {
    window.localStorage.setItem("hero_active_chart", activeChart);
  } catch {
    // Ignore unavailable storage; the in-memory tab state still works.
  }
}

interface DailyProgressProps {
  totalCalories: number;
  totalBurnedCalories: number;
  goalCalories: number;
  protein: number;
  carbs: number;
  fat: number;
}

const chartTooltipContentStyle = {
  backgroundColor: "hsl(var(--popover))",
  border: "1px solid hsl(var(--border))",
  borderRadius: "8px",
  boxShadow: "0 4px 12px hsl(var(--foreground) / 0.12)",
  color: "hsl(var(--popover-foreground))",
  fontSize: "12px",
} satisfies CSSProperties;

export function DailyProgress({
  totalCalories,
  totalBurnedCalories,
  goalCalories,
  protein,
  carbs,
  fat,
}: DailyProgressProps) {
  const t = useT();
  const [activeChart, setActiveChart] = useState(readActiveChart);

  useEffect(() => {
    writeActiveChart(activeChart);
  }, [activeChart]);

  const netCalories = totalCalories - totalBurnedCalories;
  const percentage = Math.max(
    0,
    Math.min(100, (netCalories / goalCalories) * 100),
  );
  const remaining = Math.max(0, goalCalories - netCalories);
  const isOver = netCalories > goalCalories;

  const endDate = formatLocalDate(new Date());
  const startDate = formatLocalDate(subDays(new Date(), 30));

  const weightHistoryQuery = useActionQuery(
    "weights-history",
    { startDate, endDate },
    { enabled: activeChart === "weight" },
  );
  const { data: rawWeightHistory, isLoading: weightLoading } =
    weightHistoryQuery;
  const weightHistory = Array.isArray(rawWeightHistory) ? rawWeightHistory : [];

  const calorieHistoryQuery = useActionQuery(
    "meals-history",
    { startDate, endDate },
    { enabled: activeChart === "activity" },
  );
  const { data: rawCalorieHistory, isLoading: calorieLoading } =
    calorieHistoryQuery;
  const calorieHistory = Array.isArray(rawCalorieHistory)
    ? rawCalorieHistory
    : [];

  const getYDomain = (data: any[], key: string) => {
    if (!data || data.length === 0) return [0, 100];
    const values = data.map((h) => h[key]);
    const min = Math.min(...values);
    const max = Math.max(...values);
    const padding = (max - min) * 0.2 || 10;
    return [Math.floor(min - padding), Math.ceil(max + padding)];
  };

  return (
    <div className="relative overflow-hidden rounded-2xl bg-card p-4 sm:p-5">
      <div className="macros-summary-grid">
        {/* Left Side */}
        <div className="space-y-8 flex flex-col justify-center">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-widest">
                {t("daily.summary")}
              </p>
            </div>
            <div className="px-3 py-1.5 rounded-full bg-muted/40 flex items-center">
              <span className="text-[10px] font-medium text-muted-foreground uppercase tracking-widest leading-none">
                {t("daily.goalWithValue", { value: goalCalories })}
              </span>
            </div>
          </div>

          <div>
            <div className="flex items-baseline gap-2 sm:gap-3">
              <span
                className={cn(
                  "text-5xl sm:text-7xl font-bold tracking-tighter text-foreground",
                  isOver && "text-red-400",
                )}
              >
                {netCalories}
              </span>
              <span className="text-base sm:text-xl font-medium text-muted-foreground uppercase tracking-widest">
                kcal
              </span>
            </div>
          </div>

          <div className="space-y-3 mt-auto">
            <div className="flex flex-wrap items-center gap-x-4 gap-y-2 sm:gap-x-6">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-emerald-400/60" />
                <span className="text-sm text-muted-foreground">
                  <span className="font-semibold text-emerald-400">
                    {totalCalories}
                  </span>{" "}
                  {t("daily.eaten")}
                </span>
              </div>
              {totalBurnedCalories > 0 && (
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-orange-400/60" />
                  <span className="text-sm text-muted-foreground">
                    <span className="font-semibold text-orange-400">
                      {totalBurnedCalories}
                    </span>{" "}
                    {t("daily.burned")}
                  </span>
                </div>
              )}
              <div className="flex items-center gap-2 ml-auto">
                <span className="text-sm text-muted-foreground">
                  <span
                    className={cn(
                      "font-semibold",
                      isOver ? "text-red-400" : "text-foreground",
                    )}
                  >
                    {remaining}
                  </span>{" "}
                  {t("daily.remaining")}
                </span>
              </div>
            </div>
            <div className="h-1.5 bg-muted rounded-full overflow-hidden">
              <div
                className={cn(
                  "h-full origin-left rounded-full transition-[transform,background-color] duration-200 ease-out motion-reduce:transition-none rtl:origin-right",
                  isOver ? "bg-red-400" : "bg-foreground",
                )}
                style={{
                  transform: `scaleX(${percentage / 100})`,
                }}
              />
            </div>
          </div>

          {(protein > 0 || carbs > 0 || fat > 0) && (
            <div className="grid grid-cols-3 gap-2 sm:gap-3">
              {[
                { label: t("meals.protein"), value: protein },
                { label: t("meals.carbs"), value: carbs },
                { label: t("meals.fat"), value: fat },
              ].map((m) => (
                <div
                  key={m.label}
                  className="p-2.5 sm:p-3 rounded-xl bg-muted/30"
                >
                  <p className="text-[10px] uppercase tracking-wider text-muted-foreground mb-1">
                    {m.label}
                  </p>
                  <p className="text-base sm:text-lg font-bold text-foreground">
                    {m.value}g
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Right Side: Charts */}
        <div className="macros-summary-chart flex-col justify-center transition-all duration-300">
          <Tabs
            value={activeChart}
            onValueChange={setActiveChart}
            className="flex flex-col space-y-6"
          >
            <div className="flex items-center justify-between">
              <TabsList className="bg-muted/40 h-8">
                <TabsTrigger
                  value="weight"
                  className="gap-2 text-[10px] uppercase tracking-wider h-6 px-3"
                >
                  <IconTrendingUp className="h-3 w-3" /> {t("weight.title")}
                </TabsTrigger>
                <TabsTrigger
                  value="activity"
                  className="gap-2 text-[10px] uppercase tracking-wider h-6 px-3"
                >
                  <IconActivity className="h-3 w-3" /> {t("daily.activity")}
                </TabsTrigger>
              </TabsList>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Link to="/analytics">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-8 px-2.5 text-[10px] uppercase tracking-widest text-muted-foreground/50 hover:text-foreground hover:bg-accent gap-2"
                      >
                        {t("daily.last30Days")}{" "}
                        <IconChartBar className="h-3.5 w-3.5" />
                      </Button>
                    </Link>
                  </TooltipTrigger>
                  <TooltipContent
                    side="bottom"
                    className="bg-popover border-border text-popover-foreground text-[10px] uppercase tracking-widest py-1.5 px-3"
                  >
                    {t("daily.viewFullAnalytics")}
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>

            <TabsContent
              value="weight"
              className="mt-0 flex-1 flex flex-col justify-center animate-in fade-in duration-500"
            >
              <div className="h-[140px] w-full">
                {weightLoading ? (
                  <Skeleton className="h-full w-full rounded-xl bg-muted" />
                ) : weightHistoryQuery.isError ? (
                  <QueryErrorState
                    compact
                    onRetry={() => void weightHistoryQuery.refetch()}
                  />
                ) : weightHistory.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart
                      data={weightHistory}
                      margin={{ top: 10, right: 10, left: -20, bottom: 0 }}
                    >
                      <XAxis dataKey="displayDate" hide />
                      <YAxis
                        domain={getYDomain(weightHistory, "weight")}
                        hide
                      />
                      <ChartTooltip
                        contentStyle={chartTooltipContentStyle}
                        cursor={{
                          stroke: "hsl(var(--muted-foreground) / 0.25)",
                        }}
                        formatter={(value: any, name: any) => [
                          `${value} lbs`,
                          name === "trendWeight"
                            ? t("daily.trend")
                            : t("daily.actual"),
                        ]}
                      />
                      <Line
                        type="monotone"
                        dataKey="weight"
                        stroke="hsl(var(--muted-foreground) / 0.35)"
                        strokeWidth={1}
                        dot={{
                          fill: "hsl(var(--muted-foreground) / 0.35)",
                          r: 2,
                        }}
                        activeDot={{
                          r: 4,
                          strokeWidth: 0,
                          fill: "hsl(var(--foreground))",
                        }}
                      />
                      <Line
                        type="monotone"
                        dataKey="trendWeight"
                        stroke="hsl(var(--foreground))"
                        strokeWidth={2}
                        dot={false}
                        activeDot={{
                          r: 4,
                          strokeWidth: 0,
                          fill: "hsl(var(--foreground))",
                        }}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-full flex items-center justify-center border border-dashed border-border rounded-xl">
                    <p className="text-xs text-muted-foreground">
                      {t("daily.noWeightData")}
                    </p>
                  </div>
                )}
              </div>
              {weightHistory.length > 0 && (
                <p className="text-[10px] uppercase tracking-widest text-muted-foreground/50 text-right mt-2">
                  {t("daily.currentWeight", {
                    weight: weightHistory[weightHistory.length - 1].weight,
                  })}
                </p>
              )}
            </TabsContent>

            <TabsContent
              value="activity"
              className="mt-0 flex-1 flex flex-col justify-center animate-in fade-in duration-500"
            >
              <div className="h-[140px] w-full">
                {calorieLoading ? (
                  <Skeleton className="h-full w-full rounded-xl bg-muted" />
                ) : calorieHistoryQuery.isError ? (
                  <QueryErrorState
                    compact
                    onRetry={() => void calorieHistoryQuery.refetch()}
                  />
                ) : calorieHistory.length > 0 ? (
                  <ResponsiveContainer width="100%" height="100%">
                    <AreaChart
                      data={calorieHistory}
                      margin={{ top: 10, right: 10, left: -20, bottom: 0 }}
                    >
                      <defs>
                        <linearGradient
                          id="colorNet"
                          x1="0"
                          y1="0"
                          x2="0"
                          y2="1"
                        >
                          <stop
                            offset="5%"
                            stopColor="hsl(var(--foreground))"
                            stopOpacity={0.1}
                          />
                          <stop
                            offset="95%"
                            stopColor="hsl(var(--foreground))"
                            stopOpacity={0}
                          />
                        </linearGradient>
                      </defs>
                      <XAxis dataKey="displayDate" hide />
                      <YAxis
                        domain={getYDomain(calorieHistory, "netCalories")}
                        hide
                      />
                      <ChartTooltip
                        contentStyle={chartTooltipContentStyle}
                        cursor={{
                          stroke: "hsl(var(--muted-foreground) / 0.25)",
                        }}
                        formatter={(value: any) => [
                          `${value} kcal`,
                          t("daily.netCalories"),
                        ]}
                      />
                      <Area
                        type="monotone"
                        dataKey="netCalories"
                        stroke="hsl(var(--foreground))"
                        strokeWidth={2}
                        fillOpacity={1}
                        fill="url(#colorNet)"
                        activeDot={{
                          r: 4,
                          strokeWidth: 0,
                          fill: "hsl(var(--foreground))",
                        }}
                      />
                    </AreaChart>
                  </ResponsiveContainer>
                ) : (
                  <div className="h-full flex items-center justify-center border border-dashed border-border rounded-xl">
                    <p className="text-xs text-muted-foreground">
                      {t("daily.noActivityData")}
                    </p>
                  </div>
                )}
              </div>
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  );
}
