"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CheckCircle2, Circle, Loader2 } from "lucide-react";
import { useEffect, useState } from "react";
import { db } from "@/lib/firebase/config";
import { doc, onSnapshot, collection, query, where } from "firebase/firestore";

interface CollectorChecklistProps {
  projectId: string;
  className?: string;
}

export function CollectorChecklist({ projectId, className }: CollectorChecklistProps) {
  const [loading, setLoading] = useState(true);
  const [currentPhase, setCurrentPhase] = useState<string | null>(null);
  const [hasDocuments, setHasDocuments] = useState(false);
  const [documentCount, setDocumentCount] = useState(0);
  const [githubConnected, setGithubConnected] = useState(false);
  const [githubRepo, setGithubRepo] = useState<string | null>(null);
  const [extensionLinked, setExtensionLinked] = useState(false);
  const [readyForNextPhase, setReadyForNextPhase] = useState(false);

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

    const unsubscribe = onSnapshot(
      doc(db, "projects", projectId),
      (snapshot) => {
        if (snapshot.exists()) {
          const data = snapshot.data();
          const phase = data?.currentPhase || 'collector';
          setCurrentPhase(phase);
          
          // Get actual state from project data
          const repo = data?.githubRepo || null;
          
          setGithubConnected(!!repo);
          setGithubRepo(repo);
          
          // Check handoff for readiness
          const handoff = data?.phaseData?.phaseHandoffs?.collector;
          setReadyForNextPhase(handoff?.readyForNextPhase || false);
          
          console.log("[CollectorChecklist] Project state:", {
            currentPhase: phase,
            githubRepo: repo,
            readyForNextPhase: handoff?.readyForNextPhase,
            userId: data?.userId, // Log the user ID
          });
          
          // Also log it prominently for easy copying
          console.log(`🆔 YOUR USER ID: ${data?.userId}`);
        } else {
          console.log("[CollectorChecklist] Project not found:", projectId);
        }
        setLoading(false);
      },
      (error) => {
        console.error("[CollectorChecklist] Error loading checklist:", error);
        setLoading(false);
      }
    );

    return () => unsubscribe();
  }, [projectId]);
  
  // Separate effect to check for linked sessions (extension linked)
  useEffect(() => {
    if (!projectId) return;
    
    console.log(`[CollectorChecklist] Querying sessions for projectId: "${projectId}"`);
    
    const sessionsRef = collection(db, 'sessions');
    const q = query(sessionsRef, where('projectId', '==', projectId));
    
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const hasLinkedSessions = !snapshot.empty;
      setExtensionLinked(hasLinkedSessions);
      console.log("[CollectorChecklist] Extension linked (sessions found):", hasLinkedSessions, `(${snapshot.size} sessions)`);
      
      // Debug: Show session IDs if found
      if (snapshot.size > 0) {
        const sessionIds = snapshot.docs.map(doc => doc.id);
        console.log("[CollectorChecklist] Found session IDs:", sessionIds);
      }
    }, (error) => {
      console.error("[CollectorChecklist] Error querying sessions:", error);
    });

    return () => unsubscribe();
  }, [projectId]);
  
  // Separate effect to count documents from knowledge_items collection
  // Count both uploaded documents AND pasted AI chat content
  useEffect(() => {
    if (!projectId) return;
    
    const q = query(
      collection(db, 'knowledge_items'),
      where('projectId', '==', projectId)
    );
    
    const unsubscribe = onSnapshot(q, (snapshot) => {
      // Filter for document types (uploaded files and pasted content)
      const docs = snapshot.docs.filter(doc => {
        const sourceType = doc.data().sourceType;
        return sourceType === 'imported_document' || sourceType === 'imported_ai_chat';
      });
      
      const count = docs.length;
      setHasDocuments(count > 0);
      setDocumentCount(count);
      console.log("[CollectorChecklist] Document count:", count, "(documents + pasted content)");
    });

    return () => unsubscribe();
  }, [projectId]);

  if (loading) {
    return (
      <div className={className}>
        <div className="mb-3">
          <h3 className="text-sm font-semibold">Setup Progress</h3>
        </div>
        <div className="flex items-center justify-center py-4">
          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
        </div>
      </div>
    );
  }

  const checklist = [
    {
      id: "documents",
      label: "Documents uploaded",
      checked: hasDocuments,
      count: documentCount,
    },
    {
      id: "github",
      label: "GitHub connected",
      checked: githubConnected,
      repo: githubRepo,
    },
    {
      id: "extension",
      label: "Extension linked",
      checked: extensionLinked,
    },
  ];

  const completedCount = checklist.filter((item) => item.checked).length;
  const progress = (completedCount / checklist.length) * 100;

  // If phase is beyond collector, show completed state
  const isCompleted = currentPhase === 'analyzed' || currentPhase === 'vision' || currentPhase === 'mvp';

  return (
    <div className={className}>
      {/* Header */}
      <div className="mb-3">
        <h3 className="text-sm font-semibold">
          {isCompleted ? '✓ Setup Complete' : 'Setup Progress'}
        </h3>
        <div className="mt-2">
          <div className="w-full bg-secondary h-2 rounded-full overflow-hidden">
            <div
              className="h-full bg-primary transition-all duration-300"
              style={{ width: `${isCompleted ? 100 : progress}%` }}
            />
          </div>
          <p className="text-xs text-muted-foreground mt-1">
            {isCompleted ? '3 of 3 complete' : `${completedCount} of ${checklist.length} complete`}
          </p>
        </div>
      </div>

      {/* Checklist Items */}
      <div className="space-y-2">
        {checklist.map((item) => (
          <div
            key={item.id}
            className={`flex items-center gap-2 py-2 px-3 rounded-md border ${
              (item.checked || isCompleted)
                ? "bg-green-50 border-green-200"
                : "bg-muted/50 border-muted text-muted-foreground opacity-60"
            }`}
          >
            {(item.checked || isCompleted) ? (
              <CheckCircle2 className="h-4 w-4 text-green-600 flex-shrink-0" />
            ) : (
              <Circle className="h-4 w-4 text-muted-foreground flex-shrink-0" />
            )}
            <div className="flex-1 min-w-0">
              <p className="text-xs font-medium">
                {item.label}
                {item.checked && item.count !== undefined && (
                  <span className="text-muted-foreground ml-1">
                    ({item.count})
                  </span>
                )}
              </p>
              {item.checked && item.repo && (
                <p className="text-[10px] text-muted-foreground truncate">
                  {item.repo}
                </p>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Ready indicator */}
      {readyForNextPhase && (
        <div className="mt-4 pt-4 border-t">
          <p className="text-xs text-green-600 font-medium">
            ✓ Ready for extraction phase
          </p>
        </div>
      )}
    </div>
  );
}

