"use client";

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { auth, db } from '@/lib/firebase/config';
import { collection, query, where, getDocs } from 'firebase/firestore';
import { Button } from '@/components/ui/button';
import { RefreshCw } from 'lucide-react';

interface ProjectDebugInfo {
  id: string;
  productName: string;
  name: string;
  slug: string;
  userId: string;
  workspacePath?: string;
  createdAt: any;
  updatedAt: any;
}

export default function DebugProjectsPage() {
  const [projects, setProjects] = useState<ProjectDebugInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [userId, setUserId] = useState<string>('');

  const loadProjects = async () => {
    setLoading(true);
    setError(null);
    try {
      const user = auth.currentUser;
      if (!user) {
        setError('Not authenticated');
        return;
      }

      setUserId(user.uid);

      const projectsRef = collection(db, 'projects');
      const projectsQuery = query(
        projectsRef,
        where('userId', '==', user.uid)
      );
      const snapshot = await getDocs(projectsQuery);

      const projectsData = snapshot.docs.map(doc => {
        const data = doc.data();
        return {
          id: doc.id,
          productName: data.productName || 'N/A',
          name: data.name || 'N/A',
          slug: data.slug || 'N/A',
          userId: data.userId || 'N/A',
          workspacePath: data.workspacePath,
          createdAt: data.createdAt,
          updatedAt: data.updatedAt,
        };
      });

      console.log('DEBUG: All projects from Firebase:', projectsData);
      setProjects(projectsData);
    } catch (err: any) {
      console.error('Error loading projects:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user) {
        loadProjects();
      } else {
        setError('Please sign in');
        setLoading(false);
      }
    });

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

  return (
    <div className="min-h-screen p-8 bg-background">
      <div className="max-w-6xl mx-auto space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold">🔍 Projects Debug Page</h1>
            <p className="text-muted-foreground mt-2">
              View all your projects and their unique IDs from Firebase
            </p>
            {userId && (
              <p className="text-xs text-muted-foreground mt-1">
                User ID: <code className="bg-muted px-2 py-1 rounded">{userId}</code>
              </p>
            )}
          </div>
          <Button onClick={loadProjects} disabled={loading}>
            <RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>

        {error && (
          <Card className="border-red-500">
            <CardContent className="pt-6">
              <p className="text-red-600">Error: {error}</p>
            </CardContent>
          </Card>
        )}

        {loading && !error && (
          <Card>
            <CardContent className="pt-6">
              <p className="text-center text-muted-foreground">Loading projects from Firebase...</p>
            </CardContent>
          </Card>
        )}

        {!loading && !error && (
          <>
            <Card>
              <CardHeader>
                <CardTitle>Summary</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <p className="text-sm text-muted-foreground">Total Projects</p>
                    <p className="text-2xl font-bold">{projects.length}</p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Unique IDs</p>
                    <p className="text-2xl font-bold">
                      {new Set(projects.map(p => p.id)).size}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground">Duplicate IDs?</p>
                    <p className={`text-2xl font-bold ${projects.length !== new Set(projects.map(p => p.id)).size ? 'text-red-500' : 'text-green-500'}`}>
                      {projects.length !== new Set(projects.map(p => p.id)).size ? 'YES ⚠️' : 'NO ✓'}
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <div className="space-y-4">
              <h2 className="text-xl font-semibold">All Projects</h2>
              {projects.map((project, index) => (
                <Card key={project.id + index}>
                  <CardHeader>
                    <CardTitle className="text-lg flex items-center justify-between">
                      <span>#{index + 1}: {project.productName}</span>
                      <a
                        href={`/marks-account/project/${project.id}/overview`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-sm text-primary hover:underline"
                      >
                        Open Overview →
                      </a>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <p className="text-muted-foreground">Project ID</p>
                        <code className="block bg-muted px-2 py-1 rounded mt-1 break-all">
                          {project.id}
                        </code>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Slug</p>
                        <code className="block bg-muted px-2 py-1 rounded mt-1 break-all">
                          {project.slug}
                        </code>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Product Name</p>
                        <p className="font-medium mt-1">{project.productName}</p>
                      </div>
                      <div>
                        <p className="text-muted-foreground">Internal Name</p>
                        <p className="font-medium mt-1">{project.name}</p>
                      </div>
                      {project.workspacePath && (
                        <div className="col-span-2">
                          <p className="text-muted-foreground">Workspace Path</p>
                          <code className="block bg-muted px-2 py-1 rounded mt-1 break-all text-xs">
                            {project.workspacePath}
                          </code>
                        </div>
                      )}
                    </div>
                    
                    <div className="flex gap-2 pt-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          navigator.clipboard.writeText(project.id);
                          alert('Project ID copied to clipboard!');
                        }}
                      >
                        Copy ID
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          const url = `/marks-account/project/${project.id}/v_ai_chat`;
                          window.open(url, '_blank');
                        }}
                      >
                        Open Chat
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          console.log('Full project data:', project);
                          alert('Check browser console for full data');
                        }}
                      >
                        Log to Console
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

