import { useState, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { RefreshCw, AlertCircle, Radar } from "lucide-react";
import SignatureListItem from "./SignatureListItem";
import { toast } from "@/hooks/use-toast";
import { useNavigate } from "react-router-dom";

interface SignatureItem {
  collectionId: string;
  collectionName: string;
  id: string;
  identifier: string;
  signame: string;
  sysid: string;
  system: string;
  type: string;
  updated?: string;
  created?: string;
  dangerous?: boolean;
}

interface ApiResponse {
  items: SignatureItem[];
}

interface SystemTrackerProps {
  initialSystem?: string;
}

const SystemTracker = ({ initialSystem }: SystemTrackerProps) => {
  const [currentSystem, setCurrentSystem] = useState<string>(initialSystem || "");
  const navigate = useNavigate();

  // Query to get current system from localhost:7000 (always enabled to track system changes)
  const { data: systemData, refetch: refetchSystem, isLoading: systemLoading } = useQuery({
    queryKey: ['currentSystem'],
    queryFn: async () => {
      const response = await fetch('http://localhost:7000');
      if (!response.ok) {
        throw new Error('Failed to fetch current system');
      }
      const text = await response.text();
      return text.trim();
    },
    refetchInterval: 1000, // Always refetch to track system changes
    retry: 3,
  });

  // Query to get signatures for the current system
  const { 
    data: signaturesData, 
    refetch: refetchSignatures, 
    isLoading: signaturesLoading,
    error: signaturesError 
  } = useQuery({
    queryKey: ['signatures', currentSystem],
    queryFn: async () => {
      if (!currentSystem) return null;
      
      const encodedSystem = encodeURIComponent(currentSystem);
      const url = `https://evebase.site.quack-lab.dev/api/collections/sigview/records?filter=(system%3D'${encodedSystem}')`;
      
      console.log('Fetching signatures for system:', currentSystem);
      console.log('API URL:', url);
      
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Failed to fetch signatures');
      }
      const data: ApiResponse = await response.json();
      return data;
    },
    enabled: !!currentSystem,
    refetchInterval: 60000, // Keep signature refresh at 1 minute
  });

  // Update current system when data changes and navigate to new system
  useEffect(() => {
    if (systemData && systemData !== currentSystem) {
      setCurrentSystem(systemData);
      navigate(`/${systemData}`);
      console.log('Current system updated to:', systemData);
      // Immediately refetch signatures when system changes
      refetchSignatures();
      toast({
        title: "System Updated",
        description: `Now tracking: ${systemData}`,
      });
    }
  }, [systemData, currentSystem, refetchSignatures, navigate]);

  // Refresh signatures every 5 seconds
  useEffect(() => {
    const refreshInterval = setInterval(() => {
      console.log('Auto-refreshing signatures...');
      if (currentSystem) {
        refetchSignatures();
      }
    }, 5000);

    // Cleanup interval on component unmount
    return () => clearInterval(refreshInterval);
  }, [refetchSignatures, currentSystem]);

  const handleRefresh = () => {
    refetchSystem();
    if (currentSystem) {
      refetchSignatures();
    }
    toast({
      title: "Refreshing Data",
      description: "Updating system and signature information...",
    });
  };

  const signatures = signaturesData?.items || [];
  const isLoading = systemLoading || signaturesLoading;

  // Sort signatures by date (newest first) and prioritize unknown types
  const sortedSignatures = [...signatures].sort((a, b) => {
    // First, prioritize unknown types
    const aIsUnknown = !a.type || a.type === '';
    const bIsUnknown = !b.type || b.type === '';
    if (aIsUnknown && !bIsUnknown) return -1;
    if (!aIsUnknown && bIsUnknown) return 1;
    
    // If both are unknown or both are known, sort by type
    if (a.type !== b.type) {
      return a.type.localeCompare(b.type);
    }
    
    // If same type, sort by date
    const dateA = a.updated || a.created || '';
    const dateB = b.updated || b.created || '';
    return dateB.localeCompare(dateA);
  });

  // Group signatures by type for better organization
  const signaturesByType = sortedSignatures.reduce((acc, sig) => {
    const type = sig.type || 'Unknown';
    if (!acc[type]) acc[type] = [];
    acc[type].push(sig);
    return acc;
  }, {} as Record<string, SignatureItem[]>);

  return (
    <div className="space-y-6">
      {/* System Status Card */}
      <Card className="bg-slate-800/50 border-slate-700">
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
          <CardTitle className="text-xl text-white flex items-center gap-2">
            <Radar className="h-5 w-5 text-blue-400" />
            {initialSystem ? 'System View' : 'Current System'}
          </CardTitle>
          <Button 
            onClick={handleRefresh} 
            disabled={isLoading}
            variant="outline"
            size="sm"
            className="bg-slate-700 border-slate-600 text-slate-200 hover:bg-slate-600"
          >
            <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              {systemLoading && !initialSystem ? (
                <div className="text-slate-400">Loading system...</div>
              ) : currentSystem ? (
                <div className="text-2xl font-bold text-white">{currentSystem}</div>
              ) : (
                <div className="text-slate-400">No system data</div>
              )}
            </div>
            <Badge variant="outline" className="bg-slate-700 text-slate-200 border-slate-600">
              {signatures.length} Signatures
            </Badge>
          </div>
        </CardContent>
      </Card>

      {/* Error Display */}
      {signaturesError && (
        <Card className="bg-red-900/20 border-red-700">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-red-400">
              <AlertCircle className="h-5 w-5" />
              <span>Error loading signatures: {signaturesError.message}</span>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Signatures Display */}
      {currentSystem && !signaturesLoading && (
        <div className="space-y-4">
          {sortedSignatures.length === 0 ? (
            <Card className="bg-slate-800/30 border-slate-700">
              <CardContent className="pt-6 text-center">
                <div className="text-slate-400">No signatures found for {currentSystem}</div>
              </CardContent>
            </Card>
          ) : (
            <Card className="bg-slate-800/30 border-slate-700">
              <CardHeader>
                <CardTitle className="text-white flex items-center justify-between">
                  <span>Signatures</span>
                  <Badge variant="outline" className="bg-slate-700 text-slate-200 border-slate-600">
                    {sortedSignatures.length} Total
                  </Badge>
                </CardTitle>
              </CardHeader>
              <CardContent className="p-0">
                <div className="divide-y divide-slate-700">
                  {sortedSignatures.map((signature) => (
                    <SignatureListItem key={signature.id} signature={signature} />
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      )}

      {/* Loading State */}
      {signaturesLoading && currentSystem && (
        <Card className="bg-slate-800/30 border-slate-700">
          <CardContent className="pt-6">
            <div className="space-y-4">
              {[...Array(6)].map((_, i) => (
                <div key={i} className="flex items-center gap-4 p-4 animate-pulse">
                  <div className="h-6 bg-slate-700 rounded w-24"></div>
                  <div className="h-4 bg-slate-600 rounded flex-1"></div>
                  <div className="h-4 bg-slate-700 rounded w-16"></div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default SystemTracker;
