// frontend/src/pages/ContentLibrary.jsx
import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { useT } from '../i18n/translations.js';
import { api } from '../context/AuthContext.jsx';
import { Card, Button, Spinner, EmptyState, Badge } from '../components/ui/index.jsx';
import ReactMarkdown from 'react-markdown';
import { FileText, Download, ArrowLeft, Trash2, Image, Loader2, ImageIcon } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import toast from 'react-hot-toast';

const TYPE_LABELS = {
  script:      '🎬 Script',
  post:        '𝕏 Post',
  blog:        '📰 Blog',
  newsletter:  '📧 Newsletter',
  thumbnail:   '🖼️ Thumbnail',
  clip:        '✂️ Clip',
  intel:       '🔍 Intel',
  outreach:    '🤝 Outreach',
  performance: '📊 Performance',
  image:       '🎨 Image',
};

const ALL_FILTER_TYPES = [
  '', 'script', 'post', 'blog', 'newsletter',
  'thumbnail', 'image', 'clip', 'intel', 'outreach',
];

export default function ContentLibrary() {
  const { user } = useAuth();
  const t = useT(user?.locale);
  const { id } = useParams();
  const [items, setItems] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [filterType, setFilterType] = useState('');
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);
  const [selectedLoading, setSelectedLoading] = useState(false);
  const [codexConnected, setCodexConnected] = useState(false);
  const [generatingImage, setGeneratingImage] = useState(null); // contentId being generated
  const [pollingJobs, setPollingJobs] = useState({}); // { jobId: contentId }

  useEffect(() => { fetchItems(); }, [page, filterType]);
  useEffect(() => { if (id) fetchItem(id); }, [id]);
  useEffect(() => { checkCodexStatus(); }, []);

  // Poll active generation jobs
  useEffect(() => {
    if (Object.keys(pollingJobs).length === 0) return;
    const interval = setInterval(async () => {
      for (const [jobId] of Object.entries(pollingJobs)) {
        try {
          const { data } = await api.get(`/codex/job/${jobId}`);
          if (data.status === 'completed') {
            toast.success('Image generated!');
            setPollingJobs(p => { const n = { ...p }; delete n[jobId]; return n; });
            setGeneratingImage(null);
            fetchItems();
          } else if (data.status === 'failed') {
            toast.error(`Image generation failed: ${data.error || 'Unknown error'}`);
            setPollingJobs(p => { const n = { ...p }; delete n[jobId]; return n; });
            setGeneratingImage(null);
          }
        } catch {}
      }
    }, 3000);
    return () => clearInterval(interval);
  }, [pollingJobs]);

  async function checkCodexStatus() {
    try {
      const { data } = await api.get('/codex/status');
      setCodexConnected(data.connected);
    } catch {}
  }

  async function fetchItems() {
    setLoading(true);
    try {
      const params = new URLSearchParams({ page, limit: 20 });
      if (filterType) params.set('type', filterType);
      const { data } = await api.get(`/content?${params}`);
      setItems(data.items || []);
      setTotal(data.total || 0);
    } catch {}
    setLoading(false);
  }

  async function fetchItem(itemId) {
    setSelectedLoading(true);
    try {
      const { data } = await api.get(`/content/${itemId}`);
      setSelected(data);
    } catch {}
    setSelectedLoading(false);
  }

  async function deleteItem(itemId) {
    if (!confirm('Delete this content?')) return;
    try {
      await api.delete(`/content/${itemId}`);
      setSelected(null);
      fetchItems();
      toast.success('Deleted');
    } catch { toast.error('Delete failed'); }
  }

  const downloadItem = (item) => {
    if (item.content_type === 'image') {
      window.open(`/api/codex/image/${item.id}`, '_blank');
    } else {
      window.open(`/api/content/${item.id}/download`, '_blank');
    }
  };

  async function generateImageFromThumbnail(thumbnailItem) {
    if (!codexConnected) {
      toast.error('Connect ChatGPT in Settings → ChatGPT to generate images');
      return;
    }
    const promptMatch = thumbnailItem.body?.match(/AI image prompt:\s*([^\n]+)/i);
    const prompt = promptMatch?.[1]?.trim();
    if (!prompt) {
      toast.error('No image prompt found in this thumbnail concept');
      return;
    }
    setGeneratingImage(thumbnailItem.id);
    try {
      const { data } = await api.post('/codex/generate-image', {
        prompt,
        file_name: `thumbnail_${thumbnailItem.id.slice(0, 8)}.png`,
      });
      setPollingJobs(p => ({ ...p, [data.jobId]: thumbnailItem.id }));
      toast('Generating image... This takes 1–3 minutes', { icon: '🎨' });
    } catch (err) {
      toast.error(err.response?.data?.message || 'Failed to start generation');
      setGeneratingImage(null);
    }
  }

  // ── Detail view ─────────────────────────────────────────────────────────────
  if (selected) {
    const isImage = selected.content_type === 'image';
    const isThumbnail = selected.content_type === 'thumbnail';

    return (
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <button onClick={() => setSelected(null)} className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-700">
            <ArrowLeft size={14} /> {t('common.back')}
          </button>
          <div className="flex-1" />
          {isThumbnail && (
            <Button
              size="sm"
              variant="secondary"
              loading={generatingImage === selected.id}
              onClick={() => generateImageFromThumbnail(selected)}
              className="flex items-center gap-2"
            >
              {generatingImage === selected.id
                ? <><Loader2 size={13} className="animate-spin" /> Generating…</>
                : <><ImageIcon size={13} /> Generate Image</>
              }
            </Button>
          )}
          {!isImage && (
            <Button size="sm" variant="secondary" onClick={() => downloadItem(selected)}>
              <Download size={14} /> {t('content.download')}
            </Button>
          )}
          {isImage && (
            <Button size="sm" variant="secondary" onClick={() => downloadItem(selected)}>
              <Download size={14} /> Download PNG
            </Button>
          )}
          <Button size="sm" variant="danger" onClick={() => deleteItem(selected.id)}>
            <Trash2 size={14} />
          </Button>
        </div>

        <Card className="p-6">
          <div className="flex items-center gap-2 mb-2">
            <Badge variant="default">{TYPE_LABELS[selected.content_type] || selected.content_type}</Badge>
            <span className="text-xs text-gray-400">{formatDistanceToNow(new Date(selected.created_at), { addSuffix: true })}</span>
          </div>
          <h1 className="text-xl font-semibold text-gray-900 mb-6">{selected.title}</h1>

          {isImage ? (
            <div className="space-y-4">
              <img
                src={`/api/codex/image/${selected.id}`}
                alt={selected.title}
                className="max-w-full rounded-xl border border-gray-200 shadow-sm"
                onError={(e) => {
                  e.target.style.display = 'none';
                  e.target.nextSibling.style.display = 'flex';
                }}
              />
              <div
                style={{ display: 'none' }}
                className="h-48 bg-gray-50 rounded-xl border border-gray-200 items-center justify-center text-gray-400 text-sm"
              >
                Image file not available
              </div>
              <p className="text-sm text-gray-500">{selected.body}</p>
            </div>
          ) : (
            <div className="prose prose-sm max-w-none text-gray-700">
              <ReactMarkdown>{selected.body}</ReactMarkdown>
            </div>
          )}
        </Card>
      </div>
    );
  }

  // ── List view ────────────────────────────────────────────────────────────────
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-gray-900">{t('content.title')}</h1>
        <span className="text-sm text-gray-400">{total} items</span>
      </div>

      {/* Type filter */}
      <div className="flex gap-2 flex-wrap">
        {ALL_FILTER_TYPES.map(type => (
          <button
            key={type}
            onClick={() => { setFilterType(type); setPage(1); }}
            className={`px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
              filterType === type ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            {type ? TYPE_LABELS[type] : t('content.all')}
          </button>
        ))}
      </div>

      {/* Generating image banner */}
      {Object.keys(pollingJobs).length > 0 && (
        <div className="flex items-center gap-3 px-4 py-3 bg-purple-50 border border-purple-200 rounded-xl text-sm text-purple-800">
          <Loader2 size={15} className="animate-spin text-purple-600 flex-shrink-0" />
          Generating {Object.keys(pollingJobs).length} image{Object.keys(pollingJobs).length > 1 ? 's' : ''}… This takes 1–3 minutes. The page will update automatically.
        </div>
      )}

      {loading ? (
        <div className="flex justify-center py-16"><Spinner size={32} /></div>
      ) : items.length === 0 ? (
        <EmptyState icon={FileText} title={t('content.noResults')} />
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {items.map(item => (
            <Card
              key={item.id}
              className="p-4 cursor-pointer hover:shadow-md transition-all hover:-translate-y-0.5"
              onClick={() => fetchItem(item.id)}
            >
              <div className="flex items-start gap-3">
                {item.content_type === 'image' ? (
                  <div className="w-12 h-12 rounded-lg bg-purple-50 border border-purple-100 flex items-center justify-center flex-shrink-0 overflow-hidden">
                    <img
                      src={`/api/codex/image/${item.id}`}
                      alt=""
                      className="w-full h-full object-cover rounded-lg"
                      onError={(e) => { e.target.style.display = 'none'; e.target.parentNode.innerHTML = '<span class="text-xl">🎨</span>'; }}
                    />
                  </div>
                ) : (
                  <span className="text-2xl flex-shrink-0">{TYPE_LABELS[item.content_type]?.slice(0, 2)}</span>
                )}
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-900 truncate">{item.title || item.content_type}</p>
                  <p className="text-xs text-gray-400 mt-0.5">{formatDistanceToNow(new Date(item.created_at), { addSuffix: true })}</p>
                  {item.preview && <p className="text-xs text-gray-500 mt-2 line-clamp-2">{item.preview}</p>}
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {/* Pagination */}
      {total > 20 && (
        <div className="flex justify-center gap-2">
          <Button variant="secondary" size="sm" disabled={page === 1} onClick={() => setPage(p => p - 1)}>← Prev</Button>
          <span className="py-2 px-3 text-sm text-gray-500">Page {page}</span>
          <Button variant="secondary" size="sm" disabled={items.length < 20} onClick={() => setPage(p => p + 1)}>Next →</Button>
        </div>
      )}
    </div>
  );
}
