"use client";

import { useEffect, useState } from "react";

interface StorageInfo {
  usedBytes: number;
  limitBytes: number | null;
  usedFormatted: string;
  limitFormatted: string;
  fraction: number;
  approaching: boolean;
  exceeded: boolean;
  isPaid: boolean;
}

interface Props {
  /** If provided, used directly instead of fetching. */
  info?: StorageInfo;
  className?: string;
  /** When true, renders nothing unless approaching or exceeded (for inline use in page headers). */
  compact?: boolean;
}

export function StorageMeter({ info: propInfo, className = "", compact = false }: Props) {
  const [info, setInfo] = useState<StorageInfo | null>(propInfo ?? null);
  const [loading, setLoading] = useState(!propInfo);

  useEffect(() => {
    if (propInfo) return;
    fetch("/api/storage-usage")
      .then(r => r.json())
      .then(setInfo)
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [propInfo]);

  if (loading) {
    return (
      <div className={`animate-pulse h-4 rounded-full bg-gray-200 dark:bg-gray-700 ${className}`} />
    );
  }

  if (!info || info.isPaid) return null;
  if (compact && !info.approaching && !info.exceeded) return null;

  const pct = Math.min(info.fraction * 100, 100);
  const barColor = info.exceeded
    ? "bg-red-500"
    : info.approaching
    ? "bg-amber-400"
    : "bg-rose-400";

  const textColor = info.exceeded
    ? "text-red-600 dark:text-red-400"
    : info.approaching
    ? "text-amber-600 dark:text-amber-400"
    : "text-gray-500 dark:text-gray-400";

  return (
    <div className={`space-y-1.5 ${className}`}>
      {/* Label */}
      <div className="flex justify-between items-center text-xs">
        <span className={`font-medium ${textColor}`}>
          {info.exceeded
            ? "Storage full"
            : info.approaching
            ? "Storage nearly full"
            : "Storage"}
        </span>
        <span className={textColor}>
          {info.usedFormatted} / {info.limitFormatted}
        </span>
      </div>

      {/* Bar */}
      <div className="h-1.5 rounded-full bg-gray-200 dark:bg-gray-700 overflow-hidden">
        <div
          className={`h-full rounded-full transition-all duration-500 ${barColor}`}
          style={{ width: `${pct}%` }}
        />
      </div>

      {/* Contextual message */}
      {info.exceeded && (
        <p className="text-xs text-red-600 dark:text-red-400">
          New uploads are paused. Your existing memories are safe.{" "}
          <a href="/settings#upgrade" className="underline font-medium">Upgrade</a> or delete some memories to continue.
        </p>
      )}
      {info.approaching && !info.exceeded && (
        <p className="text-xs text-amber-600 dark:text-amber-400">
          You&apos;ve used {info.usedFormatted} of {info.limitFormatted}.
        </p>
      )}
    </div>
  );
}

/**
 * Banner shown inline when an upload is blocked by the quota.
 * Drop this next to the upload button; it only renders when blocked.
 */
export function StorageQuotaBanner({
  usedBytes,
  limitBytes,
  usedFormatted,
  limitFormatted,
}: {
  usedBytes: number;
  limitBytes: number;
  usedFormatted: string;
  limitFormatted: string;
}) {
  return (
    <div className="rounded-xl border border-red-200 bg-red-50 dark:bg-red-900/20 dark:border-red-800 p-4 space-y-1">
      <p className="text-sm font-semibold text-red-700 dark:text-red-300">Storage full</p>
      <p className="text-sm text-red-600 dark:text-red-400">
        You&apos;ve used {usedFormatted} of your {limitFormatted} free-tier storage.
        Your memories are safe — new uploads are paused until you free up space or upgrade.
      </p>
      <a
        href="/settings#upgrade"
        className="inline-block mt-2 text-sm font-medium text-rose-600 dark:text-rose-400 underline"
      >
        Upgrade to continue uploading →
      </a>
    </div>
  );
}

/**
 * Banner for the child limit (shown when adding a second baby is blocked).
 */
export function ChildLimitBanner({
  currentCount,
  limit,
}: {
  currentCount: number;
  limit: number;
}) {
  return (
    <div className="rounded-xl border border-amber-200 bg-amber-50 dark:bg-amber-900/20 dark:border-amber-800 p-4 space-y-1">
      <p className="text-sm font-semibold text-amber-700 dark:text-amber-300">Baby limit reached</p>
      <p className="text-sm text-amber-600 dark:text-amber-400">
        Your free plan supports {limit} baby profile. You already have {currentCount}. Upgrade to track multiple children.
      </p>
      <a
        href="/settings#upgrade"
        className="inline-block mt-2 text-sm font-medium text-rose-600 dark:text-rose-400 underline"
      >
        Upgrade to add more →
      </a>
    </div>
  );
}

/**
 * Banner for the member limit (shown when invite is blocked).
 */
export function MemberLimitBanner({
  currentCount,
  limit,
}: {
  currentCount: number;
  limit: number;
}) {
  return (
    <div className="rounded-xl border border-amber-200 bg-amber-50 dark:bg-amber-900/20 dark:border-amber-800 p-4 space-y-1">
      <p className="text-sm font-semibold text-amber-700 dark:text-amber-300">Member limit reached</p>
      <p className="text-sm text-amber-600 dark:text-amber-400">
        Your family has {currentCount} of {limit} free-tier members. Upgrade to invite
        more caregivers.
      </p>
      <a
        href="/settings#upgrade"
        className="inline-block mt-2 text-sm font-medium text-rose-600 dark:text-rose-400 underline"
      >
        Upgrade to add more members →
      </a>
    </div>
  );
}
