'use client';

import { useState } from 'react';
import { Article, updateArticle } from '@/lib/api';
import { Calendar, Newspaper, Hash, Smile, Frown, Meh, Image as ImageIcon, Edit2, Save, X } from 'lucide-react';
import { cn } from '@/lib/utils';

interface ArticleCardProps {
  article: Article;
}

export function ArticleCard({ article: initialArticle }: ArticleCardProps) {
  const [article, setArticle] = useState(initialArticle);
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState({ category: article.category, summary: article.summary });
  const [isSaving, setIsSaving] = useState(false);

  // Determine sentiment badge
  const sentimentScore = parseFloat(article.sentiment || "0");
  const isPositive = sentimentScore > 0.3;
  const isNegative = sentimentScore < -0.3;
  
  const imageUrl = article.image_path 
    ? `/api/images/${article.image_path.replace('/data/storage/', '')}` 
    : null;

  const handleSave = async () => {
    setIsSaving(true);
    try {
      const updated = await updateArticle(article.id, {
        category: editData.category,
        summary: editData.summary
      });
      setArticle(updated);
      setIsEditing(false);
    } catch (e) {
      console.error(e);
      alert("Failed to save changes");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className={cn(
      "group relative flex flex-col gap-4 rounded-2xl border bg-zinc-900/50 p-6 transition-all hover:bg-zinc-900 hover:shadow-xl hover:shadow-indigo-500/5 hover:-translate-y-1",
      (article as any).human_verified ? "border-indigo-500/50" : "border-zinc-800"
    )}>
      {/* Header info */}
      <div className="flex items-start justify-between">
        <div className="flex flex-wrap items-center gap-3 text-xs font-medium text-zinc-400">
          <span className="flex items-center gap-1.5 rounded-full bg-zinc-800/50 px-2.5 py-1">
            <Newspaper size={14} className="text-zinc-500" />
            {article.newspaper} ({article.edition}) - P.{article.page}
          </span>
          <span className="flex items-center gap-1.5 rounded-full bg-zinc-800/50 px-2.5 py-1">
            <Calendar size={14} className="text-zinc-500" />
            {article.date}
          </span>
          <span className="flex items-center gap-1.5 rounded-full bg-zinc-800/50 px-2.5 py-1">
            <Hash size={14} className="text-zinc-500" />
            {isEditing ? (
              <input 
                type="text" 
                value={editData.category}
                onChange={e => setEditData({...editData, category: e.target.value})}
                className="bg-zinc-950 border border-zinc-700 px-1 py-0.5 rounded text-zinc-200"
              />
            ) : (
              <>{article.category} {article.subcategory ? `/ ${article.subcategory}` : ''}</>
            )}
          </span>
          {(article as any).human_verified && (
            <span className="text-indigo-400 font-bold ml-2">✓ Verified</span>
          )}
        </div>
        
        {/* Actions & Sentiment Badge */}
        <div className="flex items-center gap-3">
          {isEditing ? (
            <div className="flex items-center gap-2">
              <button onClick={handleSave} disabled={isSaving} className="flex items-center gap-1 text-xs text-emerald-400 bg-emerald-400/10 hover:bg-emerald-400/20 px-2 py-1 rounded">
                <Save size={14} /> {isSaving ? "Saving..." : "Save"}
              </button>
              <button onClick={() => { setIsEditing(false); setEditData({ category: article.category, summary: article.summary }); }} className="flex items-center gap-1 text-xs text-rose-400 bg-rose-400/10 hover:bg-rose-400/20 px-2 py-1 rounded">
                <X size={14} /> Cancel
              </button>
            </div>
          ) : (
            <button onClick={() => setIsEditing(true)} className="flex items-center gap-1 text-xs text-zinc-400 hover:text-indigo-400 transition-colors bg-zinc-800/50 hover:bg-zinc-800 px-2 py-1 rounded">
              <Edit2 size={14} /> Edit
            </button>
          )}

          <div className={cn(
            "flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold",
            isPositive ? "bg-emerald-500/10 text-emerald-400" : 
            isNegative ? "bg-rose-500/10 text-rose-400" : 
            "bg-blue-500/10 text-blue-400"
          )}>
            {isPositive ? <Smile size={14} /> : isNegative ? <Frown size={14} /> : <Meh size={14} />}
            {isPositive ? "Positive" : isNegative ? "Negative" : "Neutral"}
          </div>
        </div>
      </div>

      {/* Title & Content */}
      <div className="flex flex-col md:flex-row gap-6">
        <div className="flex-1 space-y-3">
          <h3 className="text-xl font-bold tracking-tight text-zinc-100 group-hover:text-indigo-400 transition-colors">
            {article.headline || "Untitled Article"}
          </h3>
          {article.subheadline && (
            <h4 className="text-sm font-medium text-zinc-400">
              {article.subheadline}
            </h4>
          )}
          
          {isEditing ? (
            <textarea 
              value={editData.summary}
              onChange={e => setEditData({...editData, summary: e.target.value})}
              className="w-full bg-zinc-950 border border-zinc-700 p-2 rounded-md text-sm text-zinc-200 min-h-[100px]"
            />
          ) : (
            <p className="text-sm leading-relaxed text-zinc-300">
              {article.summary || article.text?.slice(0, 250) + "..."}
            </p>
          )}
        </div>

        {/* Optional Image */}
        {imageUrl ? (
          <div className="shrink-0">
            <img 
              src={imageUrl} 
              alt="Article snippet" 
              className="h-32 w-48 object-cover rounded-xl border border-zinc-800 bg-zinc-950"
              onError={(e) => {
                e.currentTarget.style.display = 'none';
              }}
            />
          </div>
        ) : (
          <div className="shrink-0 flex h-32 w-48 items-center justify-center rounded-xl border border-dashed border-zinc-800 bg-zinc-900/50 text-zinc-600">
            <ImageIcon size={24} />
          </div>
        )}
      </div>

      {/* Entities / Tags */}
      <div className="mt-2 flex flex-wrap gap-2">
        {article.persons?.map(p => (
          <span key={`p-${p}`} className="rounded-md bg-indigo-500/10 px-2 py-1 text-xs font-medium text-indigo-400 border border-indigo-500/20">
            👤 {p}
          </span>
        ))}
        {article.locations?.map(l => (
          <span key={`l-${l}`} className="rounded-md bg-amber-500/10 px-2 py-1 text-xs font-medium text-amber-400 border border-amber-500/20">
            📍 {l}
          </span>
        ))}
        {article.organizations?.map(o => (
          <span key={`o-${o}`} className="rounded-md bg-cyan-500/10 px-2 py-1 text-xs font-medium text-cyan-400 border border-cyan-500/20">
            🏢 {o}
          </span>
        ))}
      </div>
    </div>
  );
}
