'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { 
  Github, 
  Gitlab,
  FolderOpen, 
  Search,
  RefreshCw,
  ExternalLink,
  GitBranch,
  Star,
  Eye,
  Code,
  Calendar,
  GitCompare,
  Brain,
  GitCommit,
  Server
} from 'lucide-react';
import { authApiClient } from '@/components/apis/authApiClients';
import { useAuth } from '@/contexts/auth-context';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

interface VcsRepoSummary {
  id: string;
  name: string;
  full_name: string;
  description?: string;
  language?: string;
  visibility: 'public' | 'private';
  provider: 'github' | 'gitlab' | 'bitbucket' | 'gitea';
  html_url: string;
  clone_url: string;
  default_branch: string;
  stargazers_count?: number;
  watchers_count?: number;
  forks_count?: number;
  updated_at: string;
  created_at: string;
}

const VcsReposPage: React.FC = () => {
  const { user, isLoading: authLoading } = useAuth();
  const router = useRouter();
  const [repositories, setRepositories] = useState<VcsRepoSummary[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [filter, setFilter] = useState<'all' | 'public' | 'private'>('all');
  const [providerFilter, setProviderFilter] = useState<'all' | 'github' | 'gitlab' | 'bitbucket' | 'gitea'>('all');
  const [aiAnalysisLoading, setAiAnalysisLoading] = useState<string | null>(null);
  const [aiAnalysisError, setAiAnalysisError] = useState<string | null>(null);

  // Redirect to sign-in if not authenticated
  useEffect(() => {
    if (!authLoading && !user) {
      const returnUrl = encodeURIComponent(window.location.pathname + window.location.search);
      router.push(`/signin?returnUrl=${returnUrl}`);
    }
  }, [user, authLoading, router]);

  // Handle OAuth callback for all providers
  useEffect(() => {
    const handleVcsCallback = async () => {
      const urlParams = new URLSearchParams(window.location.search);
      const oauthSuccess = urlParams.get('oauth_success');
      const provider = urlParams.get('provider');
      const attachRepo = urlParams.get('attach_repo');
      const repositoryUrl = urlParams.get('repository_url');
      const branchName = urlParams.get('branch_name');
      
      // Handle OAuth success redirect from backend
      if (oauthSuccess === 'true' && provider) {
        console.log(`🔐 [VCS OAuth] OAuth success for ${provider.toUpperCase()}`);
        
        if (attachRepo === 'true' && repositoryUrl) {
          console.log(`🔄 [VCS OAuth] Auto-attaching repository after OAuth: ${repositoryUrl}`);
          
          try {
            // Automatically attach the repository
            const response = await authApiClient.post(`/api/vcs/${provider}/attach-repository`, {
              repository_url: repositoryUrl,
              branch_name: branchName || undefined,
              user_id: user.id
            }, {
              headers: {
                'x-user-id': user.id
              }
            });
            
            if (response.data?.success) {
              alert(`✅ ${provider.toUpperCase()} account connected and repository attached successfully!`);
              
              // Clean up URL parameters
              const newUrl = window.location.pathname;
              window.history.replaceState({}, document.title, newUrl);
              
              // Refresh repositories to show the new one
              loadRepositories();
            } else {
              alert(`${provider.toUpperCase()} account connected, but failed to attach repository. Please try again.`);
            }
          } catch (attachError) {
            console.error('Failed to attach repository after OAuth:', attachError);
            alert(`${provider.toUpperCase()} account connected, but failed to attach repository. Please try again.`);
          }
        } else {
          console.log(`🔐 [VCS OAuth] ${provider.toUpperCase()} account connected successfully`);
          alert(`${provider.toUpperCase()} account connected successfully!`);
          
          // Clean up URL parameters
          const newUrl = window.location.pathname;
          window.history.replaceState({}, document.title, newUrl);
          
          // Refresh repositories
          loadRepositories();
        }
      }
    };
    
    handleVcsCallback();
  }, [user, loadRepositories]);

  // Show loading while checking authentication
  if (authLoading) {
    return (
      <div className="max-w-7xl mx-auto p-6">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <RefreshCw className="h-8 w-8 animate-spin mx-auto mb-4" />
            <p className="text-muted-foreground">Loading...</p>
          </div>
        </div>
      </div>
    );
  }

  // Show sign-in prompt if not authenticated
  if (!user) {
    return (
      <div className="max-w-7xl mx-auto p-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Authentication Required</h1>
          <p className="text-muted-foreground mb-6">
            Please sign in to view your repositories from GitHub, GitLab, Bitbucket, and Gitea.
          </p>
          <div className="space-y-4">
            <Button asChild size="lg">
              <Link href="/signin">Sign In to Continue</Link>
            </Button>
            <div className="text-sm text-muted-foreground">
              After signing in, you can connect your VCS accounts and view all your repositories in one place.
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Load repositories from all providers
  const loadRepositories = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      const allRepos: VcsRepoSummary[] = [];
      
      // Try to load from each provider
      const providers = ['github', 'gitlab', 'bitbucket', 'gitea'];
      
      for (const provider of providers) {
        try {
          const response = await authApiClient.get(`/api/vcs/${provider}/repositories`, {
            headers: {
              'x-user-id': user.id
            }
          });
          const repos = response.data?.data || [];
          
          // Add provider info to each repo
          const reposWithProvider = repos.map((repo: any) => ({
            ...repo,
            provider: provider
          }));
          
          allRepos.push(...reposWithProvider);
        } catch (err) {
          console.log(`No ${provider} repositories or not connected:`, err);
        }
      }
      
      setRepositories(allRepos);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load repositories');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadRepositories();
  }, []);

  const handleRefresh = async () => {
    await loadRepositories();
  };

  const handleAiAnalysis = async (repositoryId: string) => {
    try {
      setAiAnalysisLoading(repositoryId);
      setAiAnalysisError(null);
      
      const response = await authApiClient.get(`/api/ai-stream/repository/${repositoryId}/ai-stream`);
      const data = response.data;
      
      console.log('AI Analysis Result:', data);
      
      alert('AI Analysis completed successfully!');
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'AI Analysis failed';
      setAiAnalysisError(errorMessage);
      console.error('AI Analysis Error:', err);
    } finally {
      setAiAnalysisLoading(null);
    }
  };

  const getProviderIcon = (provider: string) => {
    switch (provider) {
      case 'github': return <Github className="h-4 w-4" />;
      case 'gitlab': return <Gitlab className="h-4 w-4" />;
      case 'bitbucket': return <GitCommit className="h-4 w-4" />;
      case 'gitea': return <Server className="h-4 w-4" />;
      default: return <GitCommit className="h-4 w-4" />;
    }
  };

  const getProviderColor = (provider: string) => {
    switch (provider) {
      case 'github': return 'bg-gray-100 text-gray-800';
      case 'gitlab': return 'bg-orange-100 text-orange-800';
      case 'bitbucket': return 'bg-blue-100 text-blue-800';
      case 'gitea': return 'bg-green-100 text-green-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const filteredRepositories = repositories.filter(repo => {
    const matchesSearch = repo.full_name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         repo.description?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         repo.language?.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesFilter = filter === 'all' || 
                         (filter === 'public' && repo.visibility === 'public') ||
                         (filter === 'private' && repo.visibility === 'private');
    
    const matchesProvider = providerFilter === 'all' || repo.provider === providerFilter;
    
    return matchesSearch && matchesFilter && matchesProvider;
  });

  return (
    <div className="container mx-auto p-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold mb-2">My Repositories</h1>
        <p className="text-gray-600">Manage and analyze your repositories from all connected providers</p>
      </div>

      {/* Search and Filters */}
      <div className="mb-6 space-y-4">
        <div className="flex gap-4">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
              <Input
                placeholder="Search repositories..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10"
              />
            </div>
          </div>
          <Button onClick={handleRefresh} disabled={isLoading} variant="outline">
            <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>

        <div className="flex gap-4">
          <div className="flex gap-2">
            <Button
              variant={filter === 'all' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setFilter('all')}
            >
              All
            </Button>
            <Button
              variant={filter === 'public' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setFilter('public')}
            >
              Public
            </Button>
            <Button
              variant={filter === 'private' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setFilter('private')}
            >
              Private
            </Button>
          </div>

          <div className="flex gap-2">
            <Button
              variant={providerFilter === 'all' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setProviderFilter('all')}
            >
              All Providers
            </Button>
            <Button
              variant={providerFilter === 'github' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setProviderFilter('github')}
            >
              <Github className="h-4 w-4 mr-1" />
              GitHub
            </Button>
            <Button
              variant={providerFilter === 'gitlab' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setProviderFilter('gitlab')}
            >
              <Gitlab className="h-4 w-4 mr-1" />
              GitLab
            </Button>
            <Button
              variant={providerFilter === 'bitbucket' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setProviderFilter('bitbucket')}
            >
              <GitCommit className="h-4 w-4 mr-1" />
              Bitbucket
            </Button>
            <Button
              variant={providerFilter === 'gitea' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setProviderFilter('gitea')}
            >
              <Server className="h-4 w-4 mr-1" />
              Gitea
            </Button>
          </div>
        </div>
      </div>

      {/* Error State */}
      {error && (
        <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-800">{error}</p>
        </div>
      )}

      {/* Loading State */}
      {isLoading && (
        <div className="flex justify-center items-center py-8">
          <RefreshCw className="h-8 w-8 animate-spin text-gray-400" />
          <span className="ml-2 text-gray-600">Loading repositories...</span>
        </div>
      )}

      {/* Repositories Grid */}
      {!isLoading && (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredRepositories.map((repo) => (
            <Card key={repo.id} className="hover:shadow-lg transition-shadow">
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center space-x-2">
                    {getProviderIcon(repo.provider)}
                    <CardTitle className="text-lg truncate">{repo.name}</CardTitle>
                  </div>
                  <Badge variant={repo.visibility === 'public' ? 'default' : 'secondary'}>
                    {repo.visibility}
                  </Badge>
                </div>
                <div className="flex items-center space-x-2">
                  <Badge className={getProviderColor(repo.provider)}>
                    {repo.provider.toUpperCase()}
                  </Badge>
                </div>
                {repo.description && (
                  <p className="text-sm text-gray-600 line-clamp-2">{repo.description}</p>
                )}
              </CardHeader>
              
              <CardContent className="pt-0">
                <div className="flex items-center space-x-4 text-sm text-gray-500 mb-4">
                  {repo.language && (
                    <div className="flex items-center space-x-1">
                      <Code className="h-4 w-4" />
                      <span>{repo.language}</span>
                    </div>
                  )}
                  <div className="flex items-center space-x-1">
                    <GitBranch className="h-4 w-4" />
                    <span>{repo.default_branch}</span>
                  </div>
                </div>

                <div className="flex items-center justify-between">
                  <div className="flex space-x-2">
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => window.open(repo.html_url, '_blank')}
                    >
                      <ExternalLink className="h-4 w-4 mr-1" />
                      View
                    </Button>
                    <Button
                      size="sm"
                      onClick={() => handleAiAnalysis(repo.id)}
                      disabled={aiAnalysisLoading === repo.id}
                    >
                      <Brain className="h-4 w-4 mr-1" />
                      {aiAnalysisLoading === repo.id ? 'Analyzing...' : 'AI Analysis'}
                    </Button>
                  </div>
                </div>

                {aiAnalysisError && (
                  <p className="text-red-600 text-sm mt-2">{aiAnalysisError}</p>
                )}
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!isLoading && filteredRepositories.length === 0 && (
        <div className="text-center py-12">
          <FolderOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">No repositories found</h3>
          <p className="text-gray-600 mb-4">
            {searchQuery || filter !== 'all' || providerFilter !== 'all' 
              ? 'Try adjusting your search or filters'
              : 'Connect your accounts to see your repositories'
            }
          </p>
          <Link href="/dashboard">
            <Button>Go to Dashboard</Button>
          </Link>
        </div>
      )}
    </div>
  );
};

export default VcsReposPage;
