'use client';

import React, { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import AppImage from '@/components/ui/AppImage';

interface Article {
  slug: string;
  title: string;
  excerpt: string;
  category: string;
  date: string;
  author: string;
  image: string;
  alt: string;
  readTime: string;
  tags: string[];
}

const TOPIC_OPTIONS = [
  'Cloud', 'AI', 'IP Workflows', 'Live Production', 'Streaming',
  'Audio', 'Cameras', 'NAB Show', 'EAS', 'Sports Broadcasting', 'Ad Tech',
];

const STORAGE_KEY_INTERESTS = 'bb_reader_interests';
const STORAGE_KEY_HISTORY = 'bb_reading_history';

interface Props {
  /** compact = horizontal card row (homepage); full = vertical list (news page) */
  variant?: 'compact' | 'full';
}

export default function AISuggestedArticles({ variant = 'compact' }: Props) {
  const [interests, setInterests] = useState<string[]>([]);
  const [suggestions, setSuggestions] = useState<Article[]>([]);
  const [loading, setLoading] = useState(false);
  const [showTopicPicker, setShowTopicPicker] = useState(false);
  const [fetched, setFetched] = useState(false);

  // Load persisted interests from localStorage
  useEffect(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY_INTERESTS);
      if (stored) setInterests(JSON.parse(stored));
    } catch {}
  }, []);

  const getReadingHistory = (): string[] => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY_HISTORY);
      return stored ? JSON.parse(stored) : [];
    } catch {
      return [];
    }
  };

  const fetchSuggestions = useCallback(async (topicList: string[]) => {
    setLoading(true);
    try {
      const history = getReadingHistory();
      const res = await fetch('/api/ai/article-suggestions', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ interests: topicList, readingHistory: history }),
      });
      if (!res.ok) throw new Error('Failed to fetch suggestions');
      const data = await res.json();
      setSuggestions(data.suggestions ?? []);
    } catch {
      setSuggestions([]);
    } finally {
      setLoading(false);
      setFetched(true);
    }
  }, []);

  // Auto-fetch on mount
  useEffect(() => {
    if (!fetched) {
      fetchSuggestions(interests);
    }
  }, [fetched, fetchSuggestions, interests]);

  const toggleInterest = (topic: string) => {
    const updated = interests.includes(topic)
      ? interests.filter((t) => t !== topic)
      : [...interests, topic];
    setInterests(updated);
    try {
      localStorage.setItem(STORAGE_KEY_INTERESTS, JSON.stringify(updated));
    } catch {}
  };

  const handleApplyTopics = () => {
    setShowTopicPicker(false);
    setFetched(false);
    fetchSuggestions(interests);
  };

  if (variant === 'full') {
    return (
      <div className="bg-[#F8FAFC] border border-[#1e1e1e] rounded-sm p-4">
        {/* Header */}
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-[#1D4ED8]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.347.346A3.5 3.5 0 0114.5 20h-5a3.5 3.5 0 01-2.47-1.024l-.347-.346z" />
            </svg>
            <h3 className="font-body font-bold text-xs text-[#1D4ED8] uppercase tracking-widest">
              AI Picks For You
            </h3>
          </div>
          <button
            onClick={() => setShowTopicPicker(!showTopicPicker)}
            className="text-[10px] font-body text-[#555] hover:text-[#1D4ED8] transition-colors flex items-center gap-1"
          >
            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
            </svg>
            Customize
          </button>
        </div>

        {/* Topic picker */}
        {showTopicPicker && (
          <div className="mb-3 p-3 bg-[#111] border border-[#222] rounded-sm">
            <p className="text-[#777] text-[10px] font-body mb-2">Select your interests:</p>
            <div className="flex flex-wrap gap-1.5 mb-3">
              {TOPIC_OPTIONS.map((topic) => (
                <button
                  key={topic}
                  onClick={() => toggleInterest(topic)}
                  className={`px-2 py-0.5 text-[10px] font-body rounded-sm border transition-colors ${
                    interests.includes(topic)
                      ? 'bg-[#1D4ED8] border-[#1D4ED8] text-white'
                      : 'bg-[#FFFFFF] border-[#DCE6F2] text-[#888] hover:border-[#1D4ED8] hover:text-[#1D4ED8]'
                  }`}
                >
                  {topic}
                </button>
              ))}
            </div>
            <button
              onClick={handleApplyTopics}
              className="text-[10px] font-body bg-[#1D4ED8] text-white px-3 py-1 rounded-sm hover:bg-[#1E3A8A] transition-colors"
            >
              Update Suggestions
            </button>
          </div>
        )}

        {/* Articles */}
        {loading ? (
          <div className="space-y-3">
            {[...Array(3)].map((_, i) => (
              <div key={i} className="flex gap-3 animate-pulse">
                <div className="w-16 h-12 bg-[#FFFFFF] rounded-sm flex-shrink-0" />
                <div className="flex-1 space-y-1.5">
                  <div className="h-2.5 bg-[#FFFFFF] rounded w-3/4" />
                  <div className="h-2.5 bg-[#FFFFFF] rounded w-1/2" />
                </div>
              </div>
            ))}
          </div>
        ) : suggestions.length > 0 ? (
          <div className="space-y-3">
            {suggestions.map((article) => (
              <Link
                key={article.slug}
                href={`/news/${article.slug}`}
                className="flex gap-3 group hover:bg-[#e2e8f0] transition-colors -mx-1 px-1 py-1 rounded-sm"
              >
                <div className="relative w-16 h-12 flex-shrink-0 overflow-hidden rounded-sm">
                  <AppImage
                    src={article.image}
                    alt={article.alt}
                    fill
                    className="object-contain group-hover:scale-105 transition-transform duration-300"
                    sizes="64px"
                  />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-[#1D4ED8] font-body text-[9px] font-bold uppercase tracking-wider mb-0.5">
                    {article.category}
                  </p>
                  <p className="font-heading text-[#0F172A] text-xs font-semibold leading-snug line-clamp-2 group-hover:text-[#1D4ED8] transition-colors">
                    {article.title}
                  </p>
                </div>
              </Link>
            ))}
          </div>
        ) : (
          <p className="text-[#555] text-xs font-body">No suggestions available.</p>
        )}
      </div>
    );
  }

  // compact variant (homepage)
  return (
    <section className="max-w-container mx-auto px-4 py-6">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2">
            <svg className="w-4 h-4 text-[#1D4ED8]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.347.346A3.5 3.5 0 0114.5 20h-5a3.5 3.5 0 01-2.47-1.024l-.347-.346z" />
            </svg>
            <span className="section-label">AI Picks For You</span>
          </div>
          <div className="flex-1 h-px bg-[#DCE6F2]" />
        </div>
        <button
          onClick={() => setShowTopicPicker(!showTopicPicker)}
          className="text-[11px] font-body text-[#555] hover:text-[#1D4ED8] transition-colors flex items-center gap-1 ml-4 shrink-0"
        >
          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4" />
          </svg>
          Customize
        </button>
      </div>

      {/* Topic picker */}
      {showTopicPicker && (
        <div className="mb-4 p-4 bg-[#111] border border-[#222] rounded-sm">
          <p className="text-[#777] text-xs font-body mb-3">Select your interests to personalize suggestions:</p>
          <div className="flex flex-wrap gap-2 mb-3">
            {TOPIC_OPTIONS.map((topic) => (
              <button
                key={topic}
                onClick={() => toggleInterest(topic)}
                className={`px-2.5 py-1 text-[11px] font-body rounded-sm border transition-colors ${
                  interests.includes(topic)
                    ? 'bg-[#1D4ED8] border-[#1D4ED8] text-white'
                    : 'bg-[#FFFFFF] border-[#DCE6F2] text-[#888] hover:border-[#1D4ED8] hover:text-[#1D4ED8]'
                }`}
              >
                {topic}
              </button>
            ))}
          </div>
          <button
            onClick={handleApplyTopics}
            className="text-xs font-body bg-[#1D4ED8] text-white px-4 py-1.5 rounded-sm hover:bg-[#1E3A8A] transition-colors"
          >
            Update Suggestions
          </button>
        </div>
      )}

      {/* Cards */}
      {loading ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="animate-pulse">
              <div className="bg-[#FFFFFF] h-[130px] rounded-sm mb-2" />
              <div className="space-y-1.5 p-1">
                <div className="h-2.5 bg-[#FFFFFF] rounded w-1/3" />
                <div className="h-3.5 bg-[#FFFFFF] rounded w-full" />
                <div className="h-3.5 bg-[#FFFFFF] rounded w-3/4" />
              </div>
            </div>
          ))}
        </div>
      ) : suggestions.length > 0 ? (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {suggestions.map((article) => (
            <Link
              key={article.slug}
              href={`/news/${article.slug}`}
              className="group block"
            >
              <div className="relative h-[130px] overflow-hidden rounded-sm mb-2">
                <AppImage
                  src={article.image}
                  alt={article.alt}
                  fill
                  className="object-contain group-hover:scale-105 transition-transform duration-300"
                  sizes="(max-width: 768px) 50vw, 25vw"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
                <span className="absolute bottom-2 left-2 text-[9px] font-body font-bold text-white uppercase tracking-wider bg-[#1D4ED8] px-1.5 py-0.5 rounded-sm">
                  {article.category}
                </span>
              </div>
              <h3 className="font-heading text-[#0F172A] text-sm font-semibold leading-snug line-clamp-2 group-hover:text-[#1D4ED8] transition-colors">
                {article.title}
              </h3>
              <p className="text-[#555] font-body text-[11px] mt-1">{article.readTime}</p>
            </Link>
          ))}
        </div>
      ) : null}
    </section>
  );
}
