import { useEffect, useState } from 'react';
import { logger } from '@/utils/logger';
import { getUserQuota, UserQuota } from '../services/uploadService';
import { TrackServiceError as TrackUploadError } from '../errors/trackErrors';
import { Progress } from '@/components/feedback/Progress';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertCircle, HardDrive, Music } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * UploadQuota Component
 * T0267: Composant pour afficher le quota d'upload utilisateur
 */

interface UploadQuotaProps {
  userId?: string;
  className?: string;
  onQuotaUpdated?: (quota: UserQuota) => void;
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${Math.round((bytes / Math.pow(k, i)) * 100) / 100} ${sizes[i]}`;
};

export function UploadQuota({
  userId = 'me',
  className,
  onQuotaUpdated,
}: UploadQuotaProps) {
  const [quota, setQuota] = useState<UserQuota | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadQuota();
  }, [userId]);

  const loadQuota = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getUserQuota(userId);
      setQuota(data);
      if (onQuotaUpdated) {
        onQuotaUpdated(data);
      }
    } catch (err) {
      const errorMessage =
        err instanceof TrackUploadError
          ? err.message
          : 'Erreur lors du chargement du quota';
      setError(errorMessage);
      logger.error('Failed to load quota:', { error: err });
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Card className={cn('w-full', className)}>
        <CardContent className="p-4">
          <div className="text-sm text-muted-foreground">
            Chargement du quota...
          </div>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card
        className={cn(
          'w-full border-destructive/50 bg-destructive/10',
          className,
        )}
      >
        <CardContent className="p-4">
          <div className="flex items-center gap-2 text-sm text-destructive">
            <AlertCircle className="h-4 w-4" />
            <span>{error}</span>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!quota) {
    return null;
  }

  const tracksPercent =
    quota.tracks_limit > 0
      ? (quota.tracks_count / quota.tracks_limit) * 100
      : 0;
  const storagePercent =
    quota.storage_limit > 0
      ? (quota.storage_used / quota.storage_limit) * 100
      : 0;

  const isQuotaNearLimit = tracksPercent >= 90 || storagePercent >= 90;
  const isQuotaExceeded = tracksPercent >= 100 || storagePercent >= 100;

  return (
    <Card
      className={cn(
        'w-full',
        className,
        isQuotaExceeded && 'border-destructive',
      )}
    >
      <CardHeader className="pb-3">
        <CardTitle className="text-sm font-medium">Quota d'upload</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Tracks quota */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2 text-sm">
              <Music className="h-4 w-4 text-muted-foreground" />
              <span className="font-medium">Tracks</span>
            </div>
            <span
              className={cn(
                'text-sm font-medium',
                isQuotaExceeded && 'text-destructive',
                isQuotaNearLimit && !isQuotaExceeded && 'text-yellow-600',
              )}
            >
              {quota.tracks_count} / {quota.tracks_limit}
            </span>
          </div>
          <Progress
            value={Math.min(tracksPercent, 100)}
            className={cn(
              isQuotaExceeded && '[&>div]:bg-destructive',
              isQuotaNearLimit && !isQuotaExceeded && '[&>div]:bg-yellow-500',
            )}
          />
          {isQuotaExceeded && (
            <p className="text-xs text-destructive mt-1">
              Limite de tracks atteinte
            </p>
          )}
        </div>

        {/* Storage quota */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2 text-sm">
              <HardDrive className="h-4 w-4 text-muted-foreground" />
              <span className="font-medium">Stockage</span>
            </div>
            <span
              className={cn(
                'text-sm font-medium',
                isQuotaExceeded && 'text-destructive',
                isQuotaNearLimit && !isQuotaExceeded && 'text-yellow-600',
              )}
            >
              {formatFileSize(quota.storage_used)} /{' '}
              {formatFileSize(quota.storage_limit)}
            </span>
          </div>
          <Progress
            value={Math.min(storagePercent, 100)}
            className={cn(
              isQuotaExceeded && '[&>div]:bg-destructive',
              isQuotaNearLimit && !isQuotaExceeded && '[&>div]:bg-yellow-500',
            )}
          />
          {isQuotaExceeded && (
            <p className="text-xs text-destructive mt-1">
              Limite de stockage atteinte
            </p>
          )}
        </div>

        {/* Warning message if quota is near limit */}
        {isQuotaNearLimit && !isQuotaExceeded && (
          <div className="flex items-start gap-2 p-2 bg-yellow-50 dark:bg-yellow-900/20 rounded-md text-xs text-yellow-800 dark:text-yellow-200">
            <AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
            <span>
              Votre quota d'upload approche de sa limite. Pensez à libérer de
              l'espace.
            </span>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
