"use client";

import { useState, useEffect } from 'react';
import { Star, GitFork, Eye, ExternalLink } from 'lucide-react';
import { Button } from './button';
import { cn } from '../../lib/utils';

interface GitHubStarsProps {
  className?: string;
  size?: 'sm' | 'md' | 'lg';
  showForks?: boolean;
  showWatchers?: boolean;
  repoUrl?: string;
}

interface GitHubStats {
  stars: number;
  forks: number;
  watchers: number;
  isLive: boolean;
}

export function GitHubStars({
  className,
  size = 'md',
  showForks = true,
  showWatchers = false,
  repoUrl = 'https://github.com/moonui/moonui'
}: GitHubStarsProps) {
  const [stats, setStats] = useState<GitHubStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch('/api/github-stars');
        const data = await response.json();
        setStats(data);
      } catch (error) {
        console.error('Failed to fetch GitHub stats:', error);
        // Set fallback data
        setStats({
          stars: 1240,
          forks: 89,
          watchers: 156,
          isLive: false
        });
      } finally {
        setIsLoading(false);
      }
    };

    fetchStats();
  }, []);

  const formatNumber = (num: number) => {
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k';
    }
    return num.toString();
  };

  const sizeClasses = {
    sm: 'text-sm gap-2',
    md: 'text-base gap-3',
    lg: 'text-lg gap-4'
  };

  const iconSizes = {
    sm: 14,
    md: 16,
    lg: 20
  };

  if (isLoading) {
    return (
      <div className={cn("flex items-center animate-pulse", sizeClasses[size], className)}>
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 bg-gray-300 dark:bg-gray-700 rounded"></div>
          <div className="w-8 h-4 bg-gray-300 dark:bg-gray-700 rounded"></div>
        </div>
        {showForks && (
          <div className="flex items-center gap-1">
            <div className="w-4 h-4 bg-gray-300 dark:bg-gray-700 rounded"></div>
            <div className="w-6 h-4 bg-gray-300 dark:bg-gray-700 rounded"></div>
          </div>
        )}
      </div>
    );
  }

  if (!stats) {
    return null;
  }

  return (
    <div className={cn("flex items-center", sizeClasses[size], className)}>
      <a
        href={repoUrl}
        target="_blank"
        rel="noopener noreferrer"
        className="flex items-center gap-1 text-gray-700 dark:text-gray-300 hover:text-primary transition-colors"
      >
        <Star className="fill-current text-yellow-500" size={iconSizes[size]} />
        <span className="font-medium">{formatNumber(stats.stars)}</span>
      </a>
      
      {showForks && (
        <a
          href={`${repoUrl}/network/members`}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center gap-1 text-gray-700 dark:text-gray-300 hover:text-primary transition-colors"
        >
          <GitFork size={iconSizes[size]} />
          <span className="font-medium">{formatNumber(stats.forks)}</span>
        </a>
      )}
      
      {showWatchers && (
        <a
          href={`${repoUrl}/watchers`}
          target="_blank"
          rel="noopener noreferrer"
          className="flex items-center gap-1 text-gray-700 dark:text-gray-300 hover:text-primary transition-colors"
        >
          <Eye size={iconSizes[size]} />
          <span className="font-medium">{formatNumber(stats.watchers)}</span>
        </a>
      )}
      
      {!stats.isLive && (
        <span className="text-xs text-gray-500 dark:text-gray-500 ml-2">
          (demo)
        </span>
      )}
    </div>
  );
}

export function GitHubStarButton({
  className,
  size = 'md',
  repoUrl = 'https://github.com/moonui/moonui'
}: {
  className?: string;
  size?: 'sm' | 'md' | 'lg';
  repoUrl?: string;
}) {
  const [stars, setStars] = useState<number | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const response = await fetch('/api/github-stars');
        const data = await response.json();
        setStars(data.stars);
      } catch (error) {
        console.error('Failed to fetch GitHub stats:', error);
        setStars(1240);
      } finally {
        setIsLoading(false);
      }
    };

    fetchStats();
  }, []);

  const formatNumber = (num: number) => {
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k';
    }
    return num.toString();
  };

  return (
    <Button
      variant="outline"
      size={size}
      className={cn("moonui-theme", "group", className)}
      asChild
    >
      <a
        href={repoUrl}
        target="_blank"
        rel="noopener noreferrer"
        className="flex items-center gap-2"
      >
        <Star className="fill-current text-yellow-500 group-hover:scale-110 transition-transform" size={16} />
        <span>Star on GitHub</span>
        {!isLoading && stars && (
          <span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-800 rounded-full text-xs font-medium">
            {formatNumber(stars)}
          </span>
        )}
        <ExternalLink size={14} className="opacity-50 group-hover:opacity-100 transition-opacity" />
      </a>
    </Button>
  );
}