'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';

interface Backlink {
  id: string;
  title: string;
  url: string;
  placement: string;
  dofollow: boolean;
  enabled: boolean;
  order: number;
  description?: string;
}

interface BacklinkAreaProps {
  placement: 'footer' | 'article' | 'category' | 'sidebar';
  className?: string;
  style?: 'inline' | 'list' | 'grid' | 'minimal';
}

// Backlink cache
let cachedBacklinks: Record<string, Backlink[]> = {};
let cacheTime = 0;
const CACHE_DURATION = 60000; // 1 dakika

async function getBacklinks(placement: string): Promise<Backlink[]> {
  const now = Date.now();
  const cacheKey = placement;

  if (cachedBacklinks[cacheKey] && now - cacheTime < CACHE_DURATION) {
    return cachedBacklinks[cacheKey];
  }

  try {
    const response = await fetch(`/api/backlinks?placement=${placement}`, { cache: 'no-store' });
    const data = await response.json();

    if (data.success && data.backlinks) {
      cachedBacklinks[cacheKey] = data.backlinks;
      cacheTime = now;
      return data.backlinks;
    }
  } catch (error) {
    console.error('Backlink yüklenemedi:', error);
  }

  return [];
}

// Footer için backlink alanı
export function FooterBacklinks({ className = '' }: { className?: string }) {
  const [links, setLinks] = useState<Backlink[]>([]);

  useEffect(() => {
    getBacklinks('footer').then(setLinks);
  }, []);

  if (links.length === 0) return null;

  return (
    <div className={`footer-backlinks ${className}`}>
      <div className="flex flex-wrap justify-center gap-x-4 gap-y-2 text-sm text-gray-400">
        {links.map((link) => (
          <a
            key={link.id}
            href={link.url}
            target="_blank"
            rel={link.dofollow ? 'dofollow' : 'nofollow noopener'}
            className="hover:text-white transition-colors"
            title={link.description || link.title}
          >
            {link.title}
          </a>
        ))}
      </div>
    </div>
  );
}

// Haber içi backlink alanı
export function ArticleBacklinks({ className = '' }: { className?: string }) {
  const [links, setLinks] = useState<Backlink[]>([]);

  useEffect(() => {
    getBacklinks('article').then(setLinks);
  }, []);

  if (links.length === 0) return null;

  return (
    <div className={`article-backlinks bg-gray-50 rounded-xl p-4 my-6 ${className}`}>
      <p className="text-xs text-gray-500 mb-2 font-medium">İlgili Bağlantılar</p>
      <div className="flex flex-wrap gap-2">
        {links.map((link) => (
          <a
            key={link.id}
            href={link.url}
            target="_blank"
            rel={link.dofollow ? 'dofollow' : 'nofollow noopener'}
            className="inline-flex items-center gap-1 px-3 py-1.5 bg-white border border-gray-200 rounded-lg text-sm text-gray-700 hover:bg-red-50 hover:border-red-200 hover:text-red-600 transition-all"
            title={link.description || link.title}
          >
            <span className="text-red-500">→</span>
            {link.title}
          </a>
        ))}
      </div>
    </div>
  );
}

// Kategori sayfası backlink alanı
export function CategoryBacklinks({ className = '' }: { className?: string }) {
  const [links, setLinks] = useState<Backlink[]>([]);

  useEffect(() => {
    getBacklinks('category').then(setLinks);
  }, []);

  if (links.length === 0) return null;

  return (
    <div className={`category-backlinks bg-gradient-to-r from-gray-50 to-gray-100 rounded-xl p-4 my-6 ${className}`}>
      <p className="text-xs text-gray-500 mb-3 font-medium uppercase tracking-wide">Önerilen Siteler</p>
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2">
        {links.map((link) => (
          <a
            key={link.id}
            href={link.url}
            target="_blank"
            rel={link.dofollow ? 'dofollow' : 'nofollow noopener'}
            className="flex items-center gap-2 px-3 py-2 bg-white rounded-lg text-sm text-gray-700 hover:shadow-md hover:text-red-600 transition-all border border-gray-100"
            title={link.description || link.title}
          >
            <span className="w-1.5 h-1.5 bg-red-500 rounded-full"></span>
            <span className="truncate">{link.title}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

// Sidebar backlink alanı
export function SidebarBacklinks({ className = '' }: { className?: string }) {
  const [links, setLinks] = useState<Backlink[]>([]);

  useEffect(() => {
    getBacklinks('sidebar').then(setLinks);
  }, []);

  if (links.length === 0) return null;

  return (
    <div className={`sidebar-backlinks bg-white rounded-xl p-4 border border-gray-100 ${className}`}>
      <h3 className="text-sm font-bold text-gray-900 mb-3 flex items-center gap-2">
        <span className="w-2 h-2 bg-red-500 rounded-full"></span>
        Faydalı Linkler
      </h3>
      <ul className="space-y-2">
        {links.map((link) => (
          <li key={link.id}>
            <a
              href={link.url}
              target="_blank"
              rel={link.dofollow ? 'dofollow' : 'nofollow noopener'}
              className="flex items-center gap-2 text-sm text-gray-600 hover:text-red-600 transition-colors group"
              title={link.description || link.title}
            >
              <span className="text-gray-400 group-hover:text-red-500 transition-colors">›</span>
              {link.title}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Genel backlink bileşeni
export default function BacklinkArea({ placement, className = '', style = 'inline' }: BacklinkAreaProps) {
  switch (placement) {
    case 'footer':
      return <FooterBacklinks className={className} />;
    case 'article':
      return <ArticleBacklinks className={className} />;
    case 'category':
      return <CategoryBacklinks className={className} />;
    case 'sidebar':
      return <SidebarBacklinks className={className} />;
    default:
      return null;
  }
}
