"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";

interface StatusLabel {
  name: string;
  class: string;
  statusType: string;
  kanbanCol: boolean | string;
  sortKey: number;
}

interface Project {
  projectId: string;
  labels: StatusLabel[];
}

export function Flow() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [retryTimeout, setRetryTimeout] = useState<NodeJS.Timeout | null>(null);

  const fetchStatusLabels = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }
      const response = await fetch('/api/leantime/status-labels');
      
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('retry-after') || '60');
        const timeout = setTimeout(() => fetchStatusLabels(), retryAfter * 1000);
        setRetryTimeout(timeout);
        setError(`Rate limit exceeded. Retrying in ${retryAfter} seconds...`);
        return;
      }

      if (!response.ok) {
        throw new Error('Failed to fetch status labels');
      }

      const data = await response.json();
      setProjects(data.projects || []);
      setError(null);
    } catch (err) {
      console.error('Error fetching status labels:', err);
      setError('Failed to fetch status labels');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    fetchStatusLabels();
    return () => {
      if (retryTimeout) {
        clearTimeout(retryTimeout);
      }
    };
  }, []);

  const getStatusClass = (className: string) => {
    switch (className) {
      case 'label-info':
      case 'label-blue':
        return 'text-blue-600';
      case 'label-warning':
        return 'text-yellow-600';
      case 'label-success':
        return 'text-green-600';
      case 'label-dark-green':
        return 'text-emerald-600';
      case 'label-important':
        return 'text-red-600';
      case 'label-default':
        return 'text-gray-600';
      default:
        return 'text-gray-600';
    }
  };

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105">
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-lg font-medium">Flow</CardTitle>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => fetchStatusLabels(true)}
          disabled={refreshing || !!retryTimeout}
          className={refreshing ? 'animate-spin' : ''}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent>
        {loading ? (
          <div className="flex items-center justify-center py-4">
            <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
          </div>
        ) : error ? (
          <div className="text-center text-sm text-red-500">{error}</div>
        ) : projects.length === 0 ? (
          <div className="text-center text-sm text-gray-500">No status labels found</div>
        ) : (
          <div className="space-y-4">
            {projects.map((project) => (
              <div key={project.projectId} className="space-y-2">
                <h3 className="font-medium text-sm">Project {project.projectId}</h3>
                <div className="space-y-1">
                  {project.labels.map((label, index) => (
                    <div key={index} className="flex justify-between items-center text-sm">
                      <span>{label.name}</span>
                      <span className={getStatusClass(label.class)}>
                        {label.statusType}
                      </span>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 