'use client';

import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { createClient } from '@/lib/supabase/client';
import Link from 'next/link';

type PipelineStatus = 'all' | 'draft' | 'scheduled' | 'published';

interface ArticleWithPerformance {
  id: string;
  title: string;
  slug: string | null;
  wp_slug: string | null;
  author_name: string | null;
  category: string | null;
  status: string;
  scheduled_at: string | null;
  date: string | null;
  source: string;
  // linked campaign data
  campaign_id: string | null;
  campaign_name: string | null;
  client_name: string | null;
  agreed_rate: number | null;
  impressions: number | null;
  clicks: number | null;
  ctr: number | null;
  campaign_status: string | null;
  campaign_start: string | null;
  campaign_end: string | null;
}

interface PipelineSummary {
  draft: number;
  scheduled: number;
  published: number;
  totalRevenue: number;
  totalImpressions: number;
  totalClicks: number;
  avgCtr: number;
}

const STATUS_COLORS: Record<string, string> = {
  draft: 'bg-yellow-900/40 text-yellow-300 border border-yellow-700/50',
  scheduled: 'bg-purple-900/40 text-purple-300 border border-purple-700/50',
  published: 'bg-green-900/40 text-green-300 border border-green-700/50',
  pending: 'bg-orange-900/40 text-orange-300 border border-orange-700/50',
  archived: 'bg-gray-800/60 text-gray-400 border border-gray-700/50',
};

const CAMPAIGN_STATUS_COLORS: Record<string, string> = {
  active: 'text-green-400',
  pending_approval: 'text-blue-400',
  pending_info: 'text-yellow-400',
  paused: 'text-gray-400',
  ended: 'text-gray-500',
  cancelled: 'text-red-400',
};

function fmt(n: number | null | undefined): string {
  if (n == null) return '—';
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M';
  if (n >= 1_000) return (n / 1_000).toFixed(1) + 'K';
  return n.toString();
}

function fmtMoney(n: number | null | undefined): string {
  if (n == null) return '—';
  return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function fmtDate(d: string | null | undefined): string {
  if (!d) return '—';
  return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export default function EditorialDashboard() {
  const { user, loading } = useAuth();
  const router = useRouter();

  const [isAdmin, setIsAdmin] = useState(false);
  const [authChecked, setAuthChecked] = useState(false);
  const [articles, setArticles] = useState<ArticleWithPerformance[]>([]);
  const [summary, setSummary] = useState<PipelineSummary | null>(null);
  const [loadingData, setLoadingData] = useState(true);
  const [statusFilter, setStatusFilter] = useState<PipelineStatus>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'date' | 'revenue' | 'impressions' | 'clicks'>('date');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');

  // Auth check
  useEffect(() => {
    if (loading) return;
    if (!user) { router.replace('/'); return; }

    const supabase = createClient();
    supabase
      .from('user_roles')
      .select('role')
      .eq('user_id', user.id)
      .single()
      .then(({ data }) => {
        if (data?.role === 'admin') {
          setIsAdmin(true);
          setAuthChecked(true);
        } else {
          router.replace('/');
        }
      });
  }, [user, loading, router]);

  const fetchData = useCallback(async () => {
    if (!isAdmin) return;
    setLoadingData(true);
    const supabase = createClient();

    // Fetch articles (both native and imported)
    const [nativeRes, importedRes, campaignsRes] = await Promise.all([
      supabase
        .from('native_articles')
        .select('id, title, slug, author_name, category, status, scheduled_at, created_at, source')
        .order('created_at', { ascending: false })
        .limit(200),
      supabase
        .from('wp_posts')
        .select('id, title, wp_slug, author_name, category, status, date')
        .order('date', { ascending: false })
        .limit(200),
      supabase
        .from('ad_campaigns')
        .select('id, campaign_name, client_name, agreed_rate, impressions, clicks, ctr, status, start_date, end_date, notes')
        .not('status', 'eq', 'cancelled'),
    ]);

    const nativeArticles: ArticleWithPerformance[] = (nativeRes.data || []).map((a: any) => ({
      id: `native-${a.id}`,
      title: a.title,
      slug: a.slug,
      wp_slug: null,
      author_name: a.author_name,
      category: a.category,
      status: a.status,
      scheduled_at: a.scheduled_at,
      date: a.created_at,
      source: 'native',
      campaign_id: null,
      campaign_name: null,
      client_name: null,
      agreed_rate: null,
      impressions: null,
      clicks: null,
      ctr: null,
      campaign_status: null,
      campaign_start: null,
      campaign_end: null,
    }));

    const importedArticles: ArticleWithPerformance[] = (importedRes.data || []).map((a: any) => ({
      id: `wp-${a.id}`,
      title: a.title,
      slug: null,
      wp_slug: a.wp_slug,
      author_name: a.author_name,
      category: a.category,
      status: a.status,
      scheduled_at: null,
      date: a.date,
      source: 'imported',
      campaign_id: null,
      campaign_name: null,
      client_name: null,
      agreed_rate: null,
      impressions: null,
      clicks: null,
      ctr: null,
      campaign_status: null,
      campaign_start: null,
      campaign_end: null,
    }));

    // Link campaigns to articles via notes field (Campaign ID: xxx) or by matching article slug in notes
    const campaigns = campaignsRes.data || [];
    const allArticles = [...nativeArticles, ...importedArticles];

    // Try to link campaigns by matching article title keywords in campaign notes or campaign_name
    const linked = allArticles.map((article) => {
      const titleWords = article.title.toLowerCase().split(' ').filter((w: string) => w.length > 4);
      const matchedCampaign = campaigns.find((c: any) => {
        const haystack = `${c.campaign_name || ''} ${c.notes || ''}`.toLowerCase();
        return titleWords.some((w: string) => haystack.includes(w));
      });
      if (matchedCampaign) {
        return {
          ...article,
          campaign_id: matchedCampaign.id,
          campaign_name: matchedCampaign.campaign_name,
          client_name: matchedCampaign.client_name,
          agreed_rate: matchedCampaign.agreed_rate,
          impressions: matchedCampaign.impressions,
          clicks: matchedCampaign.clicks,
          ctr: matchedCampaign.ctr,
          campaign_status: matchedCampaign.status,
          campaign_start: matchedCampaign.start_date,
          campaign_end: matchedCampaign.end_date,
        };
      }
      return article;
    });

    setArticles(linked);

    // Build summary
    const draft = linked.filter(a => a.status === 'draft').length;
    const scheduled = linked.filter(a => a.status === 'scheduled' || a.scheduled_at).length;
    const published = linked.filter(a => a.status === 'published').length;
    const totalRevenue = linked.reduce((sum, a) => sum + (a.agreed_rate || 0), 0);
    const totalImpressions = linked.reduce((sum, a) => sum + (a.impressions || 0), 0);
    const totalClicks = linked.reduce((sum, a) => sum + (a.clicks || 0), 0);
    const avgCtr = totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0;

    setSummary({ draft, scheduled, published, totalRevenue, totalImpressions, totalClicks, avgCtr });
    setLoadingData(false);
  }, [isAdmin]);

  useEffect(() => {
    if (isAdmin) fetchData();
  }, [isAdmin, fetchData]);

  // Filter + sort
  const filtered = articles
    .filter(a => {
      if (statusFilter === 'draft') return a.status === 'draft';
      if (statusFilter === 'scheduled') return a.status === 'scheduled' || !!a.scheduled_at;
      if (statusFilter === 'published') return a.status === 'published';
      return true;
    })
    .filter(a => {
      if (!searchQuery) return true;
      const q = searchQuery.toLowerCase();
      return (
        a.title.toLowerCase().includes(q) ||
        (a.author_name || '').toLowerCase().includes(q) ||
        (a.category || '').toLowerCase().includes(q) ||
        (a.client_name || '').toLowerCase().includes(q) ||
        (a.campaign_name || '').toLowerCase().includes(q)
      );
    })
    .sort((a, b) => {
      let av = 0, bv = 0;
      if (sortBy === 'date') {
        av = new Date(a.date || a.scheduled_at || 0).getTime();
        bv = new Date(b.date || b.scheduled_at || 0).getTime();
      } else if (sortBy === 'revenue') {
        av = a.agreed_rate || 0; bv = b.agreed_rate || 0;
      } else if (sortBy === 'impressions') {
        av = a.impressions || 0; bv = b.impressions || 0;
      } else if (sortBy === 'clicks') {
        av = a.clicks || 0; bv = b.clicks || 0;
      }
      return sortDir === 'desc' ? bv - av : av - bv;
    });

  function toggleSort(col: typeof sortBy) {
    if (sortBy === col) setSortDir(d => d === 'desc' ? 'asc' : 'desc');
    else { setSortBy(col); setSortDir('desc'); }
  }

  function SortIcon({ col }: { col: typeof sortBy }) {
    if (sortBy !== col) return <span className="text-[#444] ml-1">↕</span>;
    return <span className="text-[#1D4ED8] ml-1">{sortDir === 'desc' ? '↓' : '↑'}</span>;
  }

  if (loading || !authChecked) {
    return (
      <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  if (!isAdmin) return null;

  return (
    <div className="min-h-screen bg-[#0a0a0a] text-[#e0e0e0]">
      {/* Header */}
      <div className="border-b border-[#1e1e1e] bg-[#F8FAFC]">
        <div className="max-w-[1400px] mx-auto px-6 py-5 flex items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-bold text-white tracking-tight">Editorial Dashboard</h1>
            <p className="text-xs text-[#666] mt-0.5">Article pipeline · Linked campaigns · Ad performance</p>
          </div>
          <div className="flex items-center gap-3">
            <Link
              href="/admin/articles"
              className="px-3 py-1.5 text-xs font-semibold bg-[#1D4ED8] hover:bg-blue-500 text-white rounded transition-colors"
            >
              + New Article
            </Link>
            <Link
              href="/dashboard/adops"
              className="px-3 py-1.5 text-xs font-semibold bg-[#FFFFFF] hover:bg-[#DCE6F2] text-[#aaa] border border-[#DCE6F2] rounded transition-colors"
            >
              Ad Ops →
            </Link>
          </div>
        </div>
      </div>

      <div className="max-w-[1400px] mx-auto px-6 py-6 space-y-6">

        {/* Summary Cards */}
        {summary && (
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3">
            {[
              { label: 'Draft', value: summary.draft, color: 'text-yellow-400', onClick: () => setStatusFilter('draft') },
              { label: 'Scheduled', value: summary.scheduled, color: 'text-purple-400', onClick: () => setStatusFilter('scheduled') },
              { label: 'Published', value: summary.published, color: 'text-green-400', onClick: () => setStatusFilter('published') },
              { label: 'Total Revenue', value: fmtMoney(summary.totalRevenue), color: 'text-emerald-400', onClick: () => toggleSort('revenue') },
              { label: 'Impressions', value: fmt(summary.totalImpressions), color: 'text-blue-400', onClick: () => toggleSort('impressions') },
              { label: 'Clicks', value: fmt(summary.totalClicks), color: 'text-cyan-400', onClick: () => toggleSort('clicks') },
              { label: 'Avg CTR', value: summary.avgCtr.toFixed(2) + '%', color: 'text-orange-400', onClick: () => {} },
            ].map((card) => (
              <button
                key={card.label}
                onClick={card.onClick}
                className="bg-[#111] border border-[#1e1e1e] rounded-lg p-4 text-left hover:border-[#DCE6F2] transition-colors cursor-pointer"
              >
                <div className={`text-xl font-bold ${card.color}`}>{card.value}</div>
                <div className="text-[11px] text-[#666] mt-1 uppercase tracking-wider">{card.label}</div>
              </button>
            ))}
          </div>
        )}

        {/* Filters */}
        <div className="flex flex-wrap items-center gap-3">
          {/* Status tabs */}
          <div className="flex items-center bg-[#111] border border-[#1e1e1e] rounded-lg overflow-hidden">
            {(['all', 'draft', 'scheduled', 'published'] as PipelineStatus[]).map((s) => (
              <button
                key={s}
                onClick={() => setStatusFilter(s)}
                className={`px-3 py-1.5 text-xs font-semibold capitalize transition-colors ${
                  statusFilter === s
                    ? 'bg-[#1D4ED8] text-white'
                    : 'text-[#666] hover:text-[#aaa]'
                }`}
              >
                {s === 'all' ? 'All' : s.charAt(0).toUpperCase() + s.slice(1)}
              </button>
            ))}
          </div>

          {/* Search */}
          <div className="relative flex-1 min-w-[200px] max-w-xs">
            <input
              type="text"
              placeholder="Search articles, clients, campaigns..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="w-full bg-[#111] border border-[#1e1e1e] rounded-lg px-3 py-1.5 text-xs text-[#ccc] placeholder-[#444] focus:outline-none focus:border-[#1D4ED8] transition-colors"
            />
            {searchQuery && (
              <button
                onClick={() => setSearchQuery('')}
                className="absolute right-2 top-1/2 -translate-y-1/2 text-[#555] hover:text-[#aaa] text-xs"
              >✕</button>
            )}
          </div>

          <div className="ml-auto text-xs text-[#555]">
            {filtered.length} article{filtered.length !== 1 ? 's' : ''}
          </div>
        </div>

        {/* Pipeline Table */}
        <div className="bg-[#F8FAFC] border border-[#1e1e1e] rounded-xl overflow-hidden">
          {loadingData ? (
            <div className="flex items-center justify-center py-20">
              <div className="w-6 h-6 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" />
            </div>
          ) : filtered.length === 0 ? (
            <div className="text-center py-20 text-[#444] text-sm">No articles found</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr className="border-b border-[#FFFFFF] bg-[#0a0a0a]">
                    <th className="text-left px-4 py-3 text-[#555] font-semibold uppercase tracking-wider w-[30%]">Article</th>
                    <th className="text-left px-3 py-3 text-[#555] font-semibold uppercase tracking-wider">Status</th>
                    <th
                      className="text-left px-3 py-3 text-[#555] font-semibold uppercase tracking-wider cursor-pointer hover:text-[#aaa] select-none"
                      onClick={() => toggleSort('date')}
                    >
                      Date <SortIcon col="date" />
                    </th>
                    <th className="text-left px-3 py-3 text-[#555] font-semibold uppercase tracking-wider">Linked Campaign</th>
                    <th
                      className="text-right px-3 py-3 text-[#555] font-semibold uppercase tracking-wider cursor-pointer hover:text-[#aaa] select-none"
                      onClick={() => toggleSort('revenue')}
                    >
                      Revenue <SortIcon col="revenue" />
                    </th>
                    <th
                      className="text-right px-3 py-3 text-[#555] font-semibold uppercase tracking-wider cursor-pointer hover:text-[#aaa] select-none"
                      onClick={() => toggleSort('impressions')}
                    >
                      Impr. <SortIcon col="impressions" />
                    </th>
                    <th
                      className="text-right px-3 py-3 text-[#555] font-semibold uppercase tracking-wider cursor-pointer hover:text-[#aaa] select-none"
                      onClick={() => toggleSort('clicks')}
                    >
                      Clicks <SortIcon col="clicks" />
                    </th>
                    <th className="text-right px-3 py-3 text-[#555] font-semibold uppercase tracking-wider">CTR</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((article, idx) => {
                    const articleStatus = article.scheduled_at && article.status !== 'published' ?'scheduled'
                      : article.status;
                    return (
                      <tr
                        key={article.id}
                        className={`border-b border-[#141414] hover:bg-[#111] transition-colors ${idx % 2 === 0 ? '' : 'bg-[#0a0a0a]/30'}`}
                      >
                        {/* Article */}
                        <td className="px-4 py-3">
                          <div className="font-medium text-[#ddd] leading-snug line-clamp-2 max-w-[340px]">
                            {article.title}
                          </div>
                          <div className="flex items-center gap-2 mt-1 flex-wrap">
                            {article.author_name && (
                              <span className="text-[#555]">{article.author_name}</span>
                            )}
                            {article.category && (
                              <span className="text-[#1D4ED8]/70 bg-[#1D4ED8]/10 px-1.5 py-0.5 rounded text-[10px]">
                                {article.category}
                              </span>
                            )}
                            <span className="text-[#444] text-[10px]">{article.source}</span>
                          </div>
                        </td>

                        {/* Status */}
                        <td className="px-3 py-3">
                          <span className={`inline-flex items-center px-2 py-0.5 rounded text-[10px] font-semibold ${STATUS_COLORS[articleStatus] || STATUS_COLORS['draft']}`}>
                            {articleStatus}
                          </span>
                          {article.scheduled_at && (
                            <div className="text-[10px] text-[#555] mt-1">{fmtDate(article.scheduled_at)}</div>
                          )}
                        </td>

                        {/* Date */}
                        <td className="px-3 py-3 text-[#666] whitespace-nowrap">
                          {fmtDate(article.date || article.scheduled_at)}
                        </td>

                        {/* Linked Campaign */}
                        <td className="px-3 py-3">
                          {article.campaign_id ? (
                            <div>
                              <div className="text-[#ccc] font-medium truncate max-w-[160px]">
                                {article.client_name || article.campaign_name}
                              </div>
                              {article.campaign_name && article.client_name && (
                                <div className="text-[#555] text-[10px] truncate max-w-[160px] mt-0.5">
                                  {article.campaign_name}
                                </div>
                              )}
                              <div className="flex items-center gap-1.5 mt-1">
                                {article.campaign_status && (
                                  <span className={`text-[10px] font-semibold ${CAMPAIGN_STATUS_COLORS[article.campaign_status] || 'text-[#666]'}`}>
                                    ● {article.campaign_status.replace('_', ' ')}
                                  </span>
                                )}
                              </div>
                              {(article.campaign_start || article.campaign_end) && (
                                <div className="text-[10px] text-[#444] mt-0.5">
                                  {fmtDate(article.campaign_start)} – {fmtDate(article.campaign_end)}
                                </div>
                              )}
                            </div>
                          ) : (
                            <span className="text-[#333] italic">No campaign</span>
                          )}
                        </td>

                        {/* Revenue */}
                        <td className="px-3 py-3 text-right">
                          {article.agreed_rate ? (
                            <span className="text-emerald-400 font-semibold">{fmtMoney(article.agreed_rate)}</span>
                          ) : (
                            <span className="text-[#333]">—</span>
                          )}
                        </td>

                        {/* Impressions */}
                        <td className="px-3 py-3 text-right text-[#888]">
                          {fmt(article.impressions)}
                        </td>

                        {/* Clicks */}
                        <td className="px-3 py-3 text-right text-[#888]">
                          {fmt(article.clicks)}
                        </td>

                        {/* CTR */}
                        <td className="px-3 py-3 text-right">
                          {article.ctr != null ? (
                            <span className={`font-semibold ${article.ctr >= 2 ? 'text-green-400' : article.ctr >= 0.5 ? 'text-yellow-400' : 'text-[#666]'}`}>
                              {article.ctr.toFixed(2)}%
                            </span>
                          ) : (
                            <span className="text-[#333]">—</span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Legend */}
        <div className="flex flex-wrap items-center gap-4 text-[10px] text-[#444]">
          <span className="font-semibold text-[#555] uppercase tracking-wider">Campaign status:</span>
          {Object.entries(CAMPAIGN_STATUS_COLORS).map(([k, v]) => (
            <span key={k} className={`${v} flex items-center gap-1`}>
              <span>●</span> {k.replace('_', ' ')}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}
