"use client"

import { usePortalDashboardQuery } from "@/services/portal"
import { format } from "date-fns"
import { de } from "date-fns/locale"
import { useTranslations } from "next-intl"
import { AlertTriangle, Calendar, Clock, Leaf } from "lucide-react"

import {
  mockPortalHistory,
  mockPortalQuota,
  mockPortalUser,
} from "@/data/mock/portal"

import { cn } from "@/lib/utils"

import { Skeleton } from "@/components/ui/skeleton"
import { PortalFooter } from "@/components/portal/portal-footer"
import { PortalNavbar } from "@/components/portal/portal-navbar"

function QuotaRing({
  used,
  limit,
  label,
  size = "lg",
}: {
  used: number
  limit: number
  label: string
  size?: "sm" | "lg"
}) {
  const t = useTranslations("portal")
  const percentage = Math.min((used / limit) * 100, 100)
  const remaining = Math.max(limit - used, 0)
  const circumference = 2 * Math.PI * 45
  const strokeDashoffset = circumference - (percentage / 100) * circumference

  const getColor = (pct: number) => {
    if (pct >= 80) return "text-red-500"
    if (pct >= 50) return "text-amber-500"
    return "text-emerald-500"
  }

  const getTrackColor = (pct: number) => {
    if (pct >= 80) return "stroke-red-500/20"
    if (pct >= 50) return "stroke-amber-500/20"
    return "stroke-emerald-500/20"
  }

  const ringSize = size === "lg" ? "w-40 h-40" : "w-28 h-28"

  return (
    <div className="flex flex-col items-center gap-2">
      <div className={cn("relative", ringSize)}>
        <svg className="w-full h-full -rotate-90" viewBox="0 0 100 100">
          <circle
            cx="50"
            cy="50"
            r="45"
            fill="none"
            strokeWidth="8"
            className={getTrackColor(percentage)}
          />
          <circle
            cx="50"
            cy="50"
            r="45"
            fill="none"
            strokeWidth="8"
            strokeLinecap="round"
            className={cn("transition-all duration-700", getColor(percentage))}
            style={{
              strokeDasharray: circumference,
              strokeDashoffset,
              stroke: "currentColor",
            }}
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span
            className={cn("font-bold", size === "lg" ? "text-2xl" : "text-lg")}
          >
            {remaining.toFixed(1)}
          </span>
          <span className="text-xs text-muted-foreground">
            {t("grams")} {t("remaining")}
          </span>
        </div>
      </div>
      <div className="text-center">
        <p className="text-sm font-medium">{label}</p>
        <p className="text-xs text-muted-foreground">
          {used.toFixed(1)}
          {t("grams")} / {limit}
          {t("grams")}
        </p>
      </div>
    </div>
  )
}

function QuotaSkeleton() {
  return (
    <div className="rounded-xl border bg-card p-6 shadow-sm">
      <Skeleton className="h-6 w-24 mb-4" />
      <div className="flex flex-wrap items-center justify-center gap-8 sm:gap-12">
        <div className="flex flex-col items-center gap-2">
          <Skeleton className="w-40 h-40 rounded-full" />
          <Skeleton className="h-4 w-20" />
        </div>
        <div className="flex flex-col items-center gap-2">
          <Skeleton className="w-40 h-40 rounded-full" />
          <Skeleton className="h-4 w-20" />
        </div>
      </div>
    </div>
  )
}

export default function PortalDashboardPage() {
  const t = useTranslations("portal")

  // React Query hook
  const { data: dashboardData, isLoading } = usePortalDashboardQuery()

  // Fall back to mock data
  const quota = dashboardData?.quotaStatus ?? mockPortalQuota
  const user = dashboardData
    ? {
        firstName: dashboardData.memberName.split(" ")[0],
        memberNumber: dashboardData.memberNumber,
        clubName: "Grüner Daumen e.V.",
        joinedAt: mockPortalUser.joinedAt,
      }
    : mockPortalUser

  const {
    dailyUsedGrams,
    dailyLimitGrams,
    monthlyUsedGrams,
    monthlyLimitGrams,
  } = quota
  const monthlyPercent = Math.round(
    (monthlyUsedGrams / monthlyLimitGrams) * 100
  )
  const dailyLimitReached = dailyUsedGrams >= dailyLimitGrams

  const lastDist = dashboardData?.lastDistribution
    ? {
        date: dashboardData.lastDistribution.recordedAt,
        strain: dashboardData.lastDistribution.strainName,
        amountGrams: dashboardData.lastDistribution.amountGrams,
      }
    : mockPortalHistory[0]

  if (isLoading) {
    return (
      <>
        <PortalNavbar />
        <main className="flex-1 w-full">
          <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-6 space-y-6">
            <Skeleton className="h-8 w-64" />
            <Skeleton className="h-5 w-48" />
            <QuotaSkeleton />
            <Skeleton className="h-24 rounded-xl" />
            <Skeleton className="h-32 rounded-xl" />
          </div>
        </main>
        <PortalFooter />
      </>
    )
  }

  return (
    <>
      <PortalNavbar />
      <main className="flex-1 w-full">
        <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-6 space-y-6">
          {/* Welcome */}
          <div>
            <h1 className="text-xl font-bold sm:text-2xl">
              {t("welcome", { name: user.firstName })}
            </h1>
            <p className="text-sm text-muted-foreground mt-1">
              {user.clubName} — {t("memberNumber")}: {user.memberNumber}
            </p>
          </div>

          {/* Under-21 notice */}
          {quota.isUnder21 && (
            <div className="rounded-lg border border-amber-500/50 bg-amber-500/10 p-3 text-sm text-amber-700 dark:text-amber-400 flex items-start gap-2">
              <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
              <span>{t("under21Notice")}</span>
            </div>
          )}

          {/* Quota warning */}
          {monthlyPercent >= 80 && (
            <div className="rounded-lg border border-red-500/50 bg-red-500/10 p-3 text-sm text-red-700 dark:text-red-400 flex items-start gap-2">
              <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
              <span>
                {t("quotaWarning", { percent: String(monthlyPercent) })}
              </span>
            </div>
          )}

          {/* Quota Rings */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <h2 className="text-lg font-semibold mb-4">{t("quota")}</h2>
            <div className="flex flex-wrap items-center justify-center gap-8 sm:gap-12">
              <QuotaRing
                used={dailyUsedGrams}
                limit={dailyLimitGrams}
                label={t("dailyQuota")}
                size="lg"
              />
              <QuotaRing
                used={monthlyUsedGrams}
                limit={monthlyLimitGrams}
                label={t("monthlyQuota")}
                size="lg"
              />
            </div>

            {/* Next available */}
            {dailyLimitReached && (
              <div className="mt-4 flex items-center justify-center gap-2 text-sm text-muted-foreground">
                <Clock className="h-4 w-4" />
                <span>
                  {t("nextAvailable")}: {t("nextAvailableTomorrow")}
                </span>
              </div>
            )}
          </div>

          {/* Last Distribution */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <h2 className="text-lg font-semibold mb-3">
              {t("lastDistribution")}
            </h2>
            {lastDist ? (
              <div className="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-6 text-sm">
                <div className="flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-muted-foreground" />
                  <span>
                    {format(new Date(lastDist.date), "dd.MM.yyyy, HH:mm", {
                      locale: de,
                    })}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <Leaf className="h-4 w-4 text-muted-foreground" />
                  <span>{lastDist.strain}</span>
                </div>
                <div className="font-medium">
                  {lastDist.amountGrams}
                  {t("grams")}
                </div>
              </div>
            ) : (
              <p className="text-sm text-muted-foreground">
                {t("noDistributions")}
              </p>
            )}
          </div>

          {/* Quick Info */}
          <div className="rounded-xl border bg-card p-6 shadow-sm">
            <h2 className="text-lg font-semibold mb-3">{t("quickInfo")}</h2>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
              <div>
                <p className="text-muted-foreground">{t("memberNumber")}</p>
                <p className="font-medium">{user.memberNumber}</p>
              </div>
              <div>
                <p className="text-muted-foreground">{t("memberSince")}</p>
                <p className="font-medium">
                  {format(new Date(user.joinedAt), "dd.MM.yyyy", {
                    locale: de,
                  })}
                </p>
              </div>
              <div>
                <p className="text-muted-foreground">{t("club")}</p>
                <p className="font-medium">{user.clubName}</p>
              </div>
            </div>
          </div>
        </div>
      </main>
      <PortalFooter />
    </>
  )
}
