import React from 'react';
import {
  useIsRateLimitModalOpen,
  useSetIsRateLimitModalOpen,
  useSetIsLoginModalOpen,
  useSetIsUpgradeModalOpen,
} from '../../contexts/UIContext';
import useRenderTracker from '../../hooks/useRenderTracker';
import { useAuth } from '../../contexts/AuthContext';
import { useFeatureFlag } from '../../featureFlags';
import { useBilling } from '../../hooks/usePlanUsage';
import { Button, ModalShell, UsageMeter } from '../ui';

const RateLimitModal: React.FC = () => {
  const isRateLimitModalOpen = useIsRateLimitModalOpen();
  const setIsRateLimitModalOpen = useSetIsRateLimitModalOpen();
  const setIsLoginModalOpen = useSetIsLoginModalOpen();
  const setIsUpgradeModalOpen = useSetIsUpgradeModalOpen();
  const { isLoggedIn } = useAuth();
  const billingEnabled = useFeatureFlag('billing');
  const billing = useBilling();

  useRenderTracker('RateLimitModal', {
    isRateLimitModalOpen,
    setIsRateLimitModalOpen,
    setIsLoginModalOpen,
    isLoggedIn,
  });

  const close = () => setIsRateLimitModalOpen(false);
  // Logged-in users on a plan that can upgrade get the upgrade path.
  const showUpgrade = isLoggedIn && billingEnabled && billing.plan !== 'pro';

  return (
    <ModalShell
      open={isRateLimitModalOpen}
      title={isLoggedIn ? 'Message limit reached' : 'Continue your conversation'}
      maxWidthClass="max-w-md"
      onClose={close}
    >
      <div className="space-y-5">
        <p className="text-sm leading-6 text-app-muted">
          {!isLoggedIn
            ? "You've reached the message limit for guests. Create a free account to continue chatting. Your current conversations will be saved to your new account."
            : showUpgrade
              ? `You've used all your messages for this period (resets ${billing.renewsAt}). Upgrade to Pro for more.`
              : "You've hit the chat limit right now. Please try again later."}
        </p>

        {showUpgrade && (
          <UsageMeter used={billing.usage.used} limit={billing.usage.limit} unlimited={billing.usage.unlimited} />
        )}

        {!isLoggedIn ? (
          <Button
            variant="primary"
            className="w-full"
            onClick={() => {
              close();
              setIsLoginModalOpen(true);
            }}
          >
            Create free account
          </Button>
        ) : showUpgrade ? (
          <div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
            <Button onClick={close}>Maybe later</Button>
            <Button
              variant="primary"
              onClick={() => {
                close();
                setIsUpgradeModalOpen(true);
              }}
            >
              Upgrade to Pro
            </Button>
          </div>
        ) : (
          <Button className="w-full" onClick={close}>
            Ok
          </Button>
        )}
      </div>
    </ModalShell>
  );
};

export default RateLimitModal;
