import { useNavigate } from 'react-router-dom';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { useNetworkUsage } from '@/hooks/use-network-usage';
import { useIsNetworkAdmin, useNetwork } from '@/hooks/use-networks';

interface ComposeQuotaIndicatorProps {
  networkId: string;
}

const SHOW_PROGRESS_AT_FRACTION = 0.7;

/**
 * Surfaces freemium quota state near compose:
 *   - Nothing below 70% used (avoid nagging).
 *   - A subtle progress pill between 70% and the limit.
 *   - A locked banner with an upgrade CTA once the limit is hit.
 *
 * Pro networks and any network still loading usage render nothing.
 */
export function ComposeQuotaIndicator({
  networkId,
}: ComposeQuotaIndicatorProps) {
  const navigate = useNavigate();
  const { data: usage } = useNetworkUsage(networkId);
  const isAdmin = useIsNetworkAdmin(networkId);
  const network = useNetwork(networkId);

  if (!usage || usage.limit == null) return null;

  const fraction = usage.used / usage.limit;
  const exhausted = usage.used >= usage.limit;

  if (exhausted) {
    return (
      <div className="pointer-events-auto flex max-w-md flex-col items-center gap-2 rounded-lg border border-border bg-background/95 px-4 py-3 text-center shadow-lg backdrop-blur">
        <div className="text-sm font-medium">
          {isAdmin
            ? `You've reached today's ${usage.limit}-message limit`
            : `This network reached today's ${usage.limit}-message limit`}
        </div>
        <div className="text-xs text-muted-foreground">
          Resets {formatResetRelative(usage.reset_at)} (
          {formatResetAbsolute(usage.reset_at)})
        </div>
        {isAdmin ? (
          <Button
            size="sm"
            onClick={() => navigate(`/${networkId}/settings?section=billing`)}
          >
            Upgrade to Pro
          </Button>
        ) : (
          <div className="text-xs text-muted-foreground">
            Ask{' '}
            <span className="font-medium text-foreground">
              {network?.admin_human.email_prefix ?? 'your admin'}
            </span>{' '}
            to upgrade to Pro
          </div>
        )}
      </div>
    );
  }

  if (fraction < SHOW_PROGRESS_AT_FRACTION) return null;

  return (
    <div
      className="pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-sm backdrop-blur"
      title={`Resets ${formatResetRelative(usage.reset_at)} at ${formatResetAbsolute(usage.reset_at)}`}
    >
      <span className="tabular-nums">
        {usage.used}/{usage.limit} today
      </span>
      <Progress value={fraction * 100} className="h-1 w-24" />
    </div>
  );
}

function formatResetRelative(resetAt: Date): string {
  const now = new Date();
  const diffMs = resetAt.getTime() - now.getTime();
  const hours = Math.max(0, Math.round(diffMs / (60 * 60 * 1000)));
  if (hours < 1) return 'soon';
  if (hours === 1) return 'in 1 hour';
  return `in ${hours} hours`;
}

function formatResetAbsolute(resetAt: Date): string {
  // Shows the user their local wall-clock time for the UTC-midnight reset,
  // so a user in UTC-8 sees "4:00 PM" instead of a relative hint alone.
  return resetAt.toLocaleTimeString(undefined, {
    hour: 'numeric',
    minute: '2-digit',
  });
}
