/**
 * Usage Limits Panel Component
 * Displays hard and monthly plan limits with usage tracking
 */

import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { AlertCircle, TrendingUp, Users, Globe, Tag, FileText, Image, Zap } from 'lucide-react';
import Badge from '../ui/badge/Badge';
import { getUsageSummary, type UsageSummary, type LimitUsage } from '../../services/billing.api';
import { useToast } from '../ui/toast/ToastContainer';

interface LimitCardProps {
  title: string;
  icon: React.ReactNode;
  usage: LimitUsage;
  type: 'hard' | 'monthly';
  daysUntilReset?: number;
  accentColor?: 'brand' | 'success' | 'warning' | 'danger' | 'info' | 'purple' | 'indigo' | 'pink' | 'teal' | 'cyan';
}

function LimitCard({ title, icon, usage, type, daysUntilReset, accentColor = 'brand' }: LimitCardProps) {
  const percentage = usage.percentage_used;
  const isWarning = percentage >= 80;
  const isDanger = percentage >= 95;
  
  // Determine progress bar color - use inline styles for dynamic colors
  let barColor = 'var(--color-brand-500)';
  let badgeVariant: 'soft' = 'soft';
  let badgeTone: 'brand' | 'warning' | 'danger' | 'success' | 'info' | 'purple' | 'indigo' | 'pink' | 'teal' | 'cyan' = accentColor;
  
  // Color mapping for progress bars
  const colorMap: Record<string, string> = {
    brand: '#0693e3',
    success: '#0bbf87',
    info: '#3b82f6',
    warning: '#ff7a00',
    danger: '#ef4444',
    purple: '#8b5cf6',
    indigo: '#6366f1',
    pink: '#ec4899',
    teal: '#14b8a6',
    cyan: '#06b6d4',
  };
  
  if (isDanger) {
    barColor = colorMap.danger;
    badgeTone = 'danger';
  } else if (isWarning) {
    barColor = colorMap.warning;
    badgeTone = 'warning';
  } else {
    barColor = colorMap[accentColor] || colorMap.brand;
  }

  return (
    <Card className="p-4 hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between mb-3">
        <div className="flex items-center gap-3">
          <div 
            className="p-2 rounded-lg" 
            style={{ 
              backgroundColor: isDanger ? 'rgba(239, 68, 68, 0.1)' : isWarning ? 'rgba(255, 122, 0, 0.1)' : `${barColor}15`,
              color: barColor 
            }}
          >
            {icon}
          </div>
          <div>
            <h3 className="font-medium text-gray-900 dark:text-white">{title}</h3>
            <p className="text-xs text-gray-500 dark:text-gray-400">
              {type === 'monthly' && daysUntilReset !== undefined
                ? `Resets in ${daysUntilReset} days`
                : 'Lifetime limit'}
            </p>
          </div>
        </div>
        <Badge variant={badgeVariant} tone={badgeTone}>{percentage}%</Badge>
      </div>

      {/* Progress Bar */}
      <div className="mb-3">
        <div className="h-2.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className="h-full transition-all duration-300 ease-out"
            style={{ 
              width: `${Math.min(percentage, 100)}%`,
              backgroundColor: barColor
            }}
          />
        </div>
      </div>

      {/* Usage Stats */}
      <div className="flex items-center justify-between text-sm">
        <span className="text-gray-600 dark:text-gray-400">
          {usage.current.toLocaleString()} / {usage.limit.toLocaleString()}
        </span>
        <span className="font-medium text-gray-900 dark:text-white">
          {usage.remaining.toLocaleString()} remaining
        </span>
      </div>

      {/* Warning Message */}
      {isWarning && (
        <div className={`mt-3 flex items-start gap-2 text-xs ${
          isDanger ? 'text-red-600 dark:text-red-400' : 'text-yellow-600 dark:text-yellow-400'
        }`}>
          <AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
          <span>
            {isDanger
              ? 'Limit almost reached! Consider upgrading your plan.'
              : 'Approaching limit. Monitor your usage carefully.'}
          </span>
        </div>
      )}
    </Card>
  );
}

export default function UsageLimitsPanel() {
  const toast = useToast();
  const [summary, setSummary] = useState<UsageSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>('');

  useEffect(() => {
    loadUsageSummary();
  }, []);

  const loadUsageSummary = async () => {
    try {
      setLoading(true);
      setError('');
      const data = await getUsageSummary();
      setSummary(data);
    } catch (err: any) {
      const message = err?.message || 'Failed to load usage summary';
      setError(message);
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="animate-pulse">
          <div className="h-32 bg-gray-200 dark:bg-gray-700 rounded-lg mb-4"></div>
          <div className="h-32 bg-gray-200 dark:bg-gray-700 rounded-lg mb-4"></div>
          <div className="h-32 bg-gray-200 dark:bg-gray-700 rounded-lg"></div>
        </div>
      </div>
    );
  }

  if (error || !summary) {
    return (
      <Card className="p-6 text-center">
        <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
        <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
          Failed to Load Usage Data
        </h3>
        <p className="text-gray-600 dark:text-gray-400 mb-4">{error || 'Unknown error'}</p>
        <button
          onClick={loadUsageSummary}
          className="px-4 py-2 bg-[var(--color-brand-500)] text-white rounded-lg hover:bg-[var(--color-brand-600)]"
        >
          Retry
        </button>
      </Card>
    );
  }

  const hardLimitConfig = {
    sites: { icon: <Globe className="w-5 h-5" />, color: 'success' as const },
    users: { icon: <Users className="w-5 h-5" />, color: 'info' as const },
    keywords: { icon: <Tag className="w-5 h-5" />, color: 'purple' as const },
    clusters: { icon: <TrendingUp className="w-5 h-5" />, color: 'warning' as const },
  };

  const monthlyLimitConfig = {
    content_ideas: { icon: <FileText className="w-5 h-5" />, color: 'brand' as const },
    content_words: { icon: <FileText className="w-5 h-5" />, color: 'indigo' as const },
    images_basic: { icon: <Image className="w-5 h-5" />, color: 'teal' as const },
    images_premium: { icon: <Zap className="w-5 h-5" />, color: 'cyan' as const },
    image_prompts: { icon: <Image className="w-5 h-5" />, color: 'pink' as const },
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">Plan Limits & Usage</h2>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Current Plan: <span className="font-medium">{summary.plan_name}</span>
          </p>
        </div>
        {summary.days_until_reset !== undefined && (
          <Badge variant="soft" tone="brand">
            Resets in {summary.days_until_reset} days
          </Badge>
        )}
      </div>

      {/* Hard Limits Section */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Account Limits
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {Object.entries(summary.hard_limits).map(([key, usage]) => {
            const config = hardLimitConfig[key as keyof typeof hardLimitConfig];
            return (
              <LimitCard
                key={key}
                title={usage.display_name}
                icon={config.icon}
                usage={usage}
                type="hard"
                accentColor={config.color}
              />
            );
          })}
        </div>
      </div>

      {/* Monthly Limits Section */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          Monthly Usage Limits
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {Object.entries(summary.monthly_limits).map(([key, usage]) => {
            const config = monthlyLimitConfig[key as keyof typeof monthlyLimitConfig];
            return (
              <LimitCard
                key={key}
                title={usage.display_name}
                icon={config.icon}
                usage={usage}
                type="monthly"
                daysUntilReset={summary.days_until_reset}
                accentColor={config.color}
              />
            );
          })}
        </div>
      </div>

      {/* Upgrade CTA if approaching limits */}
      {(Object.values(summary.hard_limits).some(u => u.percentage_used >= 80) ||
        Object.values(summary.monthly_limits).some(u => u.percentage_used >= 80)) && (
        <Card className="p-6 bg-gradient-to-r from-brand-50 to-brand-100 dark:from-brand-900/20 dark:to-brand-800/10 border-brand-200 dark:border-brand-700">
          <div className="flex items-start gap-4">
            <div className="p-3 bg-brand-500 rounded-lg text-white">
              <TrendingUp className="w-6 h-6" />
            </div>
            <div className="flex-1">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                Approaching Your Limits
              </h3>
              <p className="text-gray-600 dark:text-gray-400 mb-4">
                You're using a significant portion of your plan's resources. Upgrade to get higher limits
                and avoid interruptions.
              </p>
              <a
                href="/account/plans?tab=upgrade"
                className="inline-flex items-center px-4 py-2 bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition-colors"
              >
                Upgrade Plan
              </a>
            </div>
          </div>
        </Card>
      )}
    </div>
  );
}
