"use client";

import Link from "next/link";
import type { ReactNode } from "react";
import { panelDict } from "@/features/panel/dict";
import { toPersianDigits } from "@/lib/to-english-digits";

type DashboardSummaryVariant = "goals" | "habits" | "tasks";

type DashboardSummaryCardProps = {
  variant: DashboardSummaryVariant;
  isLoading: boolean;
  progressPill?: string;
  activeCount: number;
  completedCount: number;
  totalCount: number;
  avgProgress?: number;
  emptyMessage?: string;
  isEmpty?: boolean;
  href: string;
  linkLabel: string;
};

function formatNumber(value: number) {
  return toPersianDigits(value.toLocaleString("fa-IR"));
}

function ChevronEndIcon({ className }: { className?: string }) {
  return (
    <svg
      aria-hidden="true"
      className={`size-6 max-h-6 max-w-6 shrink-0 text-primary/80 ${className ?? ""}`}
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={2}
    >
      <path d="M15 6l-6 6 6 6" />
    </svg>
  );
}

function CalendarIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-primary"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <rect x="4" y="5" width="16" height="15" rx="2" />
      <path d="M8 3v4M16 3v4M4 10h16" />
    </svg>
  );
}

function TrendIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-[#2EC4B6]"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <path d="M4 16l4-4 4 3 8-9" />
      <path d="M17 6h3v3" />
    </svg>
  );
}

function ClipboardIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-[#9B59B6]"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <rect x="7" y="4" width="10" height="4" rx="1" />
      <path d="M9 4V3h6v1M8 8h8v12H8z" />
    </svg>
  );
}

function ListIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-[#9B59B6]"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <path d="M9 6h12M9 12h12M9 18h12" />
      <circle cx="5" cy="6" r="1" fill="currentColor" stroke="none" />
      <circle cx="5" cy="12" r="1" fill="currentColor" stroke="none" />
      <circle cx="5" cy="18" r="1" fill="currentColor" stroke="none" />
    </svg>
  );
}

function DocumentIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-[#9B59B6]"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={1.75}
    >
      <path d="M8 4h8l4 4v12H8z" />
      <path d="M16 4v4h4" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      aria-hidden="true"
      className="size-4 text-[#2EC4B6]"
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={2}
    >
      <path d="M5 12l4 4 10-10" />
    </svg>
  );
}

function GoalsProgressBar({ percent }: { percent: number }) {
  const clampedPercent = Math.min(100, Math.max(0, percent));

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between gap-3 text-sm">
        <span className="text-muted-foreground">{panelDict.avgGoalProgress}</span>
        <span className="font-semibold text-primary">
          {toPersianDigits(clampedPercent)}٪
        </span>
      </div>
      <div className="h-2 overflow-hidden rounded-full bg-muted">
        <div
          className="h-full rounded-full bg-primary transition-[width]"
          style={{ width: `${clampedPercent}%` }}
        />
      </div>
    </div>
  );
}

function StatTile({
  label,
  icon,
  children,
  success = false,
}: {
  label: string;
  icon?: ReactNode;
  children: ReactNode;
  success?: boolean;
}) {
  return (
    <div
      className={`flex min-h-[7.5rem] flex-col items-center justify-between rounded-2xl px-3 py-3 text-center ${
        success ? "bg-[#2EC4B6]/10" : "bg-muted/50"
      }`}
    >
      <div className="flex flex-1 flex-col items-center justify-center gap-2">
        {children}
        <p className="text-[11px] text-muted-foreground sm:text-xs">{label}</p>
      </div>
      {icon ? (
        <div className="mt-2 inline-flex size-8 items-center justify-center rounded-xl bg-card/80">
          {icon}
        </div>
      ) : null}
    </div>
  );
}

const variantMeta: Record<
  DashboardSummaryVariant,
  { title: string; subtitle?: string; icon: ReactNode }
> = {
  goals: {
    title: panelDict.goalsSummary,
    subtitle: undefined,
    icon: <CalendarIcon />,
  },
  habits: {
    title: panelDict.habitsSummary,
    icon: <TrendIcon />,
  },
  tasks: {
    title: panelDict.tasksSummary,
    icon: <ClipboardIcon />,
  },
};

export function DashboardSummaryCard({
  variant,
  isLoading,
  progressPill,
  activeCount,
  completedCount,
  totalCount,
  avgProgress = 0,
  emptyMessage,
  isEmpty = false,
  href,
  linkLabel,
}: DashboardSummaryCardProps) {
  const meta = variantMeta[variant];

  return (
    <section className="rounded-3xl bg-card p-4 shadow-soft-sm sm:p-5">
      <div className="mb-4 flex items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            {meta.icon}
            <h2 className="text-base font-bold text-card-foreground sm:text-lg">
              {meta.title}
            </h2>
          </div>
          {meta.subtitle ? (
            <p className="mt-1 text-xs text-muted-foreground sm:text-sm">
              {meta.subtitle}
            </p>
          ) : null}
        </div>

        {!isLoading && progressPill ? (
          <span className="shrink-0 rounded-full bg-muted px-2.5 py-1 text-[10px] text-muted-foreground sm:text-[11px]">
            {progressPill}
          </span>
        ) : null}
      </div>

      {isLoading ? (
        <p className="text-sm text-muted-foreground">{panelDict.loading}</p>
      ) : variant === "goals" && activeCount > 0 ? (
        <GoalsProgressBar percent={avgProgress} />
      ) : variant !== "goals" ? (
        <div className="grid grid-cols-2 gap-2.5">
          <StatTile
            label={
              variant === "habits"
                ? panelDict.activeHabits
                : panelDict.totalTasks
            }
            icon={variant === "habits" ? <ListIcon /> : <DocumentIcon />}
          >
            <p className="text-2xl font-bold text-card-foreground">
              {formatNumber(variant === "habits" ? activeCount : totalCount)}
            </p>
          </StatTile>

          <StatTile
            label={
              variant === "habits"
                ? panelDict.habitsCompletedToday
                : panelDict.completedTasks
            }
            icon={<CheckIcon />}
            success
          >
            <p className="text-2xl font-bold text-[#2EC4B6]">
              {formatNumber(completedCount)}
            </p>
          </StatTile>
        </div>
      ) : null}

      {!isLoading && isEmpty && emptyMessage ? (
        <p className="mt-3 text-center text-xs text-muted-foreground sm:text-sm">
          {emptyMessage}
        </p>
      ) : null}

      <Link
        href={href}
        className="relative mt-4 flex h-11 w-full items-center justify-center rounded-2xl border border-border/60 bg-muted/40 px-4 text-sm font-semibold text-primary transition-colors hover:bg-muted/60"
      >
        <ChevronEndIcon className="absolute end-4" />
        {linkLabel}
      </Link>
    </section>
  );
}
