"use client";

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { auth, db } from '@/lib/firebase/config';
import { doc, getDoc } from 'firebase/firestore';
import { toast } from 'sonner';
import { Loader2, Link as LinkIcon, CheckCircle2 } from 'lucide-react';
import { useParams } from 'next/navigation';

interface Project {
  id: string;
  productName: string;
  githubRepo?: string;
  workspacePath?: string;
}

export default function AssociateSessionsPage() {
  const params = useParams();
  const projectId = params.projectId as string;
  const [project, setProject] = useState<Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [associating, setAssociating] = useState(false);
  const [result, setResult] = useState<any>(null);

  useEffect(() => {
    loadProject();
  }, [projectId]);

  const loadProject = async () => {
    try {
      const projectDoc = await getDoc(doc(db, 'projects', projectId));
      if (projectDoc.exists()) {
        setProject({ id: projectDoc.id, ...projectDoc.data() } as Project);
      }
    } catch (error) {
      console.error('Error loading project:', error);
      toast.error('Failed to load project');
    } finally {
      setLoading(false);
    }
  };

  const handleAssociateSessions = async () => {
    if (!project?.githubRepo) {
      toast.error('Project does not have a GitHub repository connected');
      return;
    }

    setAssociating(true);
    setResult(null);

    try {
      const user = auth.currentUser;
      if (!user) {
        toast.error('Please sign in');
        return;
      }

      const token = await user.getIdToken();
      const response = await fetch(`/api/projects/${projectId}/associate-github-sessions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          githubRepo: project.githubRepo,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setResult(data);
        
        if (data.sessionsAssociated > 0) {
          toast.success(`Success!`, {
            description: `Linked ${data.sessionsAssociated} existing chat sessions to this project`,
          });
        } else {
          toast.info('No unassociated sessions found for this repository');
        }
      } else {
        const error = await response.json();
        toast.error(error.error || 'Failed to associate sessions');
      }
    } catch (error) {
      console.error('Error:', error);
      toast.error('An error occurred');
    } finally {
      setAssociating(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="container max-w-4xl mx-auto p-8 space-y-6">
      <div>
        <h1 className="text-3xl font-bold">Associate Existing Sessions</h1>
        <p className="text-muted-foreground mt-2">
          Find and link chat sessions from this GitHub repository
        </p>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Project Details</CardTitle>
          <CardDescription>Current project configuration</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <p className="text-sm text-muted-foreground">Product Name</p>
            <p className="font-medium">{project?.productName}</p>
          </div>
          
          {project?.githubRepo && (
            <div>
              <p className="text-sm text-muted-foreground">GitHub Repository</p>
              <p className="font-medium font-mono text-sm">{project.githubRepo}</p>
            </div>
          )}
          
          {project?.workspacePath && (
            <div>
              <p className="text-sm text-muted-foreground">Workspace Path</p>
              <p className="font-medium font-mono text-sm">{project.workspacePath}</p>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Find Matching Sessions</CardTitle>
          <CardDescription>
            Search your database for chat sessions that match this project's GitHub repository
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="bg-muted/50 p-4 rounded-lg space-y-2 text-sm">
            <p><strong>How it works:</strong></p>
            <ul className="list-disc list-inside space-y-1 text-muted-foreground">
              <li>Searches for sessions with matching GitHub repository</li>
              <li>Also checks sessions from matching workspace paths</li>
              <li>Only links sessions that aren't already assigned to a project</li>
              <li>Updates all matched sessions to link to this project</li>
            </ul>
          </div>

          <Button 
            onClick={handleAssociateSessions}
            disabled={!project?.githubRepo || associating}
            className="w-full"
            size="lg"
          >
            {associating ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Searching...
              </>
            ) : (
              <>
                <LinkIcon className="mr-2 h-4 w-4" />
                Find and Link Sessions
              </>
            )}
          </Button>

          {!project?.githubRepo && (
            <p className="text-sm text-muted-foreground text-center">
              Connect a GitHub repository first to use this feature
            </p>
          )}
        </CardContent>
      </Card>

      {result && (
        <Card className="border-green-500/50 bg-green-50/50 dark:bg-green-950/20">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-green-600">
              <CheckCircle2 className="h-5 w-5" />
              Results
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">Sessions Linked</p>
                <p className="text-2xl font-bold">{result.sessionsAssociated}</p>
              </div>
              
              {result.details && (
                <>
                  <div>
                    <p className="text-sm text-muted-foreground">Exact GitHub Matches</p>
                    <p className="text-2xl font-bold">{result.details.exactMatches}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Path Matches</p>
                    <p className="text-2xl font-bold">{result.details.pathMatches}</p>
                  </div>
                </>
              )}
            </div>
            
            <p className="text-sm text-muted-foreground">
              {result.message}
            </p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

