"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";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

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

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

export function Flow() {
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const router = useRouter();
  const { data: session } = useSession();

  const fetchStatusLabels = async (isRefresh = false) => {
    try {
      if (isRefresh) {
        setRefreshing(true);
      }
      const response = await fetch('/api/leantime/status-labels', {
        cache: 'no-store',
        next: { revalidate: 0 },
      });
      
      if (response.status === 401) {
        setError('Session expired. Please sign in again.');
        return;
      }

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.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);
      const errorMessage = err instanceof Error ? err.message : 'Failed to fetch status labels';
      setError(errorMessage);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    if (session) {
      fetchStatusLabels();
      // Set up polling every 5 minutes
      const interval = setInterval(() => fetchStatusLabels(), 300000);
      return () => clearInterval(interval);
    }
  }, [session]);

  return (
    <Card 
      className="transition-transform duration-500 ease-in-out transform hover:scale-105 cursor-pointer bg-white/50 backdrop-blur-sm h-full" 
      onClick={() => router.push('/flow')}
    >
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-lg font-semibold">Flow</CardTitle>
        <Button 
          variant="ghost" 
          size="icon"
          onClick={(e) => {
            e.stopPropagation();
            fetchStatusLabels(true);
          }}
          disabled={refreshing}
          className={refreshing ? 'animate-spin' : ''}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {loading && <p className="text-center text-muted-foreground">Loading status labels...</p>}
        {error && (
          <div className="text-center">
            <p className="text-red-500">Error: {error}</p>
            <Button 
              variant="outline" 
              onClick={(e) => {
                e.stopPropagation();
                fetchStatusLabels(true);
              }}
              className="mt-2"
            >
              Try Again
            </Button>
          </div>
        )}
        {!loading && !error && (
          <div className="space-y-4 max-h-[300px] overflow-y-auto">
            {projects.length === 0 ? (
              <p className="text-center text-muted-foreground">No status labels found</p>
            ) : (
              projects.map((project) => (
                <div key={project.projectId} className="space-y-2">
                  <h3 className="text-sm font-medium text-gray-500">Project {project.projectId}</h3>
                  <div className="space-y-1">
                    {project.labels.map((label) => (
                      <div 
                        key={`${project.projectId}-${label.id}`}
                        className="flex items-start space-x-2 hover:bg-gray-50 p-2 rounded-lg transition-colors"
                      >
                        <div className="flex-1 min-w-0">
                          <div className="flex items-baseline justify-between">
                            <p className="text-sm font-medium truncate">{label.name}</p>
                            <span className={`text-xs px-2 py-1 rounded ${label.class}`}>
                              {label.statusType}
                            </span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
} 