import { Link, usePage } from '@inertiajs/react';

import { Button } from '@/Components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/Components/ui/dialog';
import { trackEvent } from '@/lib/analytics';
import { BYOK_SETUP_PROMPTED, QUOTA_EXHAUSTED_UPGRADE_CLICKED } from '@/lib/event-catalog';
import type { PageProps } from '@/types';

interface QuotaExhaustedModalProps {
  open: boolean;
  onClose: () => void;
  limit: number;
  resetDate: string;
  proPriceMonthly?: number;
  proDraftsPerMonth?: number;
}

export default function QuotaExhaustedModal({
  open,
  onClose,
  limit,
  resetDate,
  proPriceMonthly: _proPriceMonthly = 49,
  proDraftsPerMonth: _proDraftsPerMonth = 30,
}: QuotaExhaustedModalProps) {
  const { limits, plan } = usePage<PageProps>().props;
  const proDrafts = limits?.pro_drafts_per_month ?? 30;
  const proPrice = limits?.pro_price ?? 49;
  const isPaidUser = !!plan && plan !== 'free';

  const [year, month, day] = resetDate.split('-').map(Number);
  const resetDateObj = new Date(year, month - 1, day);
  const daysUntilReset = Math.ceil((resetDateObj.getTime() - Date.now()) / 86400000);
  const formattedDate = resetDateObj.toLocaleDateString('en-US', { month: 'long', day: 'numeric' });

  return (
    <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
      <DialogContent className="max-w-md" aria-labelledby="quota-modal-title">
        <DialogHeader>
          <DialogTitle id="quota-modal-title">
            You've used all {limit} free AI drafts this month
          </DialogTitle>
          <DialogDescription>
            Your drafts reset on {formattedDate}{' '}
            {daysUntilReset > 0 && `(${daysUntilReset} day${daysUntilReset === 1 ? '' : 's'} away)`}
            .
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 pt-2">
          <p className="text-sm text-muted-foreground">Want more drafts right now?</p>

          {isPaidUser ? (
            <Button asChild className="w-full">
              <Link
                href={route('settings.ai')}
                onClick={() => trackEvent(BYOK_SETUP_PROMPTED)}
              >
                Set up your OpenAI key for unlimited drafts at ~$0.05/draft
              </Link>
            </Button>
          ) : (
            <Button asChild className="w-full">
              <Link
                href={route('billing.plans')}
                onClick={() => trackEvent(QUOTA_EXHAUSTED_UPGRADE_CLICKED)}
              >
                Upgrade to Pro — {proDrafts} drafts/month · ${proPrice}
              </Link>
            </Button>
          )}

          <Button variant="ghost" className="w-full" onClick={onClose}>
            Dismiss
          </Button>

          {!isPaidUser && (
            <p className="text-xs text-center text-muted-foreground">
              Note: Bring Your Own Key (BYOK) requires a Pro plan or higher
            </p>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
