import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Loader2, CheckCircle2, AlertCircle, Clock } from "lucide-react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { supabase } from "@/lib/supabase";
import { useTranslation } from 'react-i18next';

interface CustomContentStatusBadgeProps {
  contentId: string;
  status: string;
  error?: string;
}

export function CustomContentStatusBadge({
  contentId,
  status: initialStatus,
  error,
}: CustomContentStatusBadgeProps) {
  const { t } = useTranslation();
  const [status, setStatus] = useState(initialStatus);
  const [polling, setPolling] = useState(
    initialStatus === "pending" || initialStatus === "processing"
  );

  useEffect(() => {
    if (!polling) return;

    const pollStatus = async () => {
      try {
        const { data: { session } } = await supabase.auth.getSession();
        if (!session) return;

        const response = await fetch(
          `${import.meta.env.VITE_API_URL}/custom-content-sync-status?content_id=${contentId}`,
          {
            headers: {
              Authorization: `Bearer ${session.access_token}`,
            },
          }
        );

        if (response.ok) {
          const result = await response.json();
          setStatus(result.status);

          // Stop polling if completed or failed
          if (result.status === "completed" || result.status === "failed") {
            setPolling(false);
          }
        }
      } catch (err) {
        console.error("Status poll error:", err);
      }
    };

    // Poll every 3 seconds
    const interval = setInterval(pollStatus, 3000);
    pollStatus(); // Initial poll

    return () => clearInterval(interval);
  }, [contentId, polling]);

  const getStatusDisplay = () => {
    switch (status) {
      case "pending":
        return {
          label: t('customContent.status.pending'),
          icon: <Clock className="h-3 w-3" />,
          variant: "secondary" as const,
          tooltip: t('customContent.status.tooltip.pending'),
        };
      case "processing":
        return {
          label: t('customContent.status.processing'),
          icon: <Loader2 className="h-3 w-3 animate-spin" />,
          variant: "default" as const,
          tooltip: t('customContent.status.tooltip.processing'),
        };
      case "completed":
        return {
          label: t('customContent.status.ready'),
          icon: <CheckCircle2 className="h-3 w-3" />,
          variant: "default" as const,
          tooltip: t('customContent.status.tooltip.ready'),
        };
      case "failed":
        return {
          label: t('customContent.status.failed'),
          icon: <AlertCircle className="h-3 w-3" />,
          variant: "destructive" as const,
          tooltip: error || t('customContent.status.tooltip.failed'),
        };
      default:
        return {
          label: status,
          icon: null,
          variant: "secondary" as const,
          tooltip: "",
        };
    }
  };

  const statusDisplay = getStatusDisplay();

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <span className="inline-flex">
            <Badge variant={statusDisplay.variant} className="gap-1">
              {statusDisplay.icon}
              {statusDisplay.label}
            </Badge>
          </span>
        </TooltipTrigger>
        <TooltipContent>
          <p>{statusDisplay.tooltip}</p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}
