'use client';

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

// ─── Types ────────────────────────────────────────────────────────────────────

interface QueueItem {
  id: string;
  company_name: string;
  source_article_title: string;
  source_article_slug: string;
  source_type: string;
  ai_draft_title: string;
  ai_draft_content: string;
  ai_draft_excerpt: string;
  status: 'queued' | 'approved' | 'published' | 'dismissed';
  reminder_sent: boolean;
  created_at: string;
}

interface AutopilotSettings {
  id?: string;
  autopilot_enabled: boolean;
  reminder_email: string;
  last_scan_at?: string;
  last_scan_articles_processed?: number;
  last_scan_companies_found?: number;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'just now';
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  return `${days}d ago`;
}

// ─── Main Page ────────────────────────────────────────────────────────────────

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

  const [queue, setQueue] = useState<QueueItem[]>([]);
  const [settings, setSettings] = useState<AutopilotSettings>({
    autopilot_enabled: false,
    reminder_email: 'ryan.salazar@relevantmediaproperties.com',
  });
  const [activeTab, setActiveTab] = useState<'queued' | 'published' | 'dismissed'>('queued');
  const [loadingData, setLoadingData] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [savingSettings, setSavingSettings] = useState(false);
  const [scanResult, setScanResult] = useState<{ articlesScanned: number; newCompaniesFound: number } | null>(null);
  const [expandedItem, setExpandedItem] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  const showToast = (message: string, type: 'success' | 'error' = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 4000);
  };

  const fetchData = useCallback(async () => {
    try {
      setLoadingData(true);
      const [queueRes, settingsRes] = await Promise.all([
        fetch(`/api/admin/company-coverage?status=${activeTab}`),
        fetch('/api/admin/company-coverage?action=settings'),
      ]);
      const queueData = await queueRes.json();
      const settingsData = await settingsRes.json();
      setQueue(queueData.queue || []);
      if (settingsData.settings) setSettings(settingsData.settings);
    } catch {
      showToast('Failed to load data', 'error');
    } finally {
      setLoadingData(false);
    }
  }, [activeTab]);

  useEffect(() => {
    if (!loading && !user) router.push('/login?next=' + encodeURIComponent(window.location.pathname));
  }, [user, loading, router]);

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

  const handleScan = async () => {
    setScanning(true);
    setScanResult(null);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'scan' }),
      });
      const data = await res.json();
      if (data.success) {
        setScanResult({ articlesScanned: data.articlesScanned, newCompaniesFound: data.newCompaniesFound });
        showToast(`Scan complete: ${data.newCompaniesFound} new companies found across ${data.articlesScanned} articles`);
        fetchData();
      } else {
        showToast(data.error || 'Scan failed', 'error');
      }
    } catch {
      showToast('Scan failed', 'error');
    } finally {
      setScanning(false);
    }
  };

  const handleToggleAutopilot = async () => {
    const newValue = !settings.autopilot_enabled;
    setSavingSettings(true);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'update_settings',
          autopilot_enabled: newValue,
          reminder_email: settings.reminder_email,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setSettings((s) => ({ ...s, autopilot_enabled: newValue }));
        showToast(newValue ? 'Auto-Pilot enabled — stories will publish automatically' : 'Auto-Pilot disabled — stories will queue for review');
      } else {
        showToast('Failed to update settings', 'error');
      }
    } catch {
      showToast('Failed to update settings', 'error');
    } finally {
      setSavingSettings(false);
    }
  };

  const handleAction = async (id: string, action: 'publish' | 'dismiss') => {
    setActionLoading(id);
    try {
      const res = await fetch('/api/admin/company-coverage', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id, action }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(action === 'publish' ? 'Story published successfully' : 'Story dismissed');
        fetchData();
      } else {
        showToast(data.error || 'Action failed', 'error');
      }
    } catch {
      showToast('Action failed', 'error');
    } finally {
      setActionLoading(null);
    }
  };

  if (loading || loadingData) {
    return (
      <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
        <div className="flex flex-col items-center gap-3">
          <div className="w-8 h-8 border-2 border-[#1D4ED8] border-t-transparent rounded-full animate-spin" />
          <p className="text-[#555] text-sm font-body">Loading company coverage…</p>
        </div>
      </div>
    );
  }

  if (!user) return null;

  return (
    <div className="min-h-screen bg-[#0a0a0a]">
      {/* Toast */}
      {toast && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg text-sm font-body shadow-lg flex items-center gap-2 ${
          toast.type === 'success' ? 'bg-green-500/20 border border-green-500/40 text-green-300' : 'bg-red-500/20 border border-red-500/40 text-red-300'
        }`}>
          {toast.type === 'success' ? (
            <svg className="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
            </svg>
          ) : (
            <svg className="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <circle cx="12" cy="12" r="10" /><path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01" />
            </svg>
          )}
          {toast.message}
        </div>
      )}

      <div className="max-w-7xl mx-auto px-4 py-8">

        {/* Header */}
        <div className="mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 mb-1">
              <Link href="/admin" className="text-[#555] hover:text-white text-sm font-body transition-colors">Admin</Link>
              <svg className="w-3.5 h-3.5 text-[#333]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
              </svg>
              <span className="text-[#888] text-sm font-body">Company Coverage</span>
            </div>
            <h1 className="text-2xl font-display font-bold text-white">Company Coverage</h1>
            <p className="text-[#555] text-sm font-body mt-1">AI-powered company story suggestions from published articles</p>
          </div>
          <button
            onClick={handleScan}
            disabled={scanning}
            className="flex items-center gap-2 px-4 py-2 bg-[#1D4ED8] hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-body font-semibold rounded-lg transition-colors"
          >
            {scanning ? (
              <>
                <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                Scanning…
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                Scan Articles Now
              </>
            )}
          </button>
        </div>

        {/* Scan Result Banner */}
        {scanResult && (
          <div className="mb-6 bg-blue-500/10 border border-blue-500/30 rounded-lg px-4 py-3 flex items-center gap-3">
            <svg className="w-4 h-4 text-blue-400 flex-shrink-0" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <p className="text-blue-300 text-sm font-body">
              Scanned <strong>{scanResult.articlesScanned}</strong> articles — found <strong>{scanResult.newCompaniesFound}</strong> new company mentions
              {settings.autopilot_enabled && <span className="text-green-400 ml-2">· Auto-published via Auto-Pilot</span>}
            </p>
          </div>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

          {/* Queue Panel */}
          <div className="lg:col-span-2">

            {/* Tabs */}
            <div className="flex gap-1 mb-4 bg-[#111] border border-[#DCE6F2] rounded-lg p-1 w-fit">
              {(['queued', 'published', 'dismissed'] as const).map((tab) => (
                <button
                  key={tab}
                  onClick={() => setActiveTab(tab)}
                  className={`px-4 py-1.5 rounded-md text-sm font-body font-semibold capitalize transition-colors ${
                    activeTab === tab
                      ? 'bg-[#1D4ED8] text-white'
                      : 'text-[#888] hover:text-white'
                  }`}
                >
                  {tab}
                </button>
              ))}
            </div>

            {/* Queue List */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg overflow-hidden">
              {queue.length === 0 ? (
                <div className="px-5 py-16 text-center">
                  <svg className="w-10 h-10 text-[#333] mx-auto mb-3" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1m2 13a2 2 0 01-2-2V7m2 13a2 2 0 002-2V9a2 2 0 00-2-2h-2m-4-3H9M7 16h6M7 12h6m-6-4h.01" />
                  </svg>
                  <p className="text-[#555] text-sm font-body">
                    {activeTab === 'queued' ? 'No stories queued — run a scan to detect companies' : `No ${activeTab} stories`}
                  </p>
                  {activeTab === 'queued' && (
                    <button onClick={handleScan} disabled={scanning} className="mt-3 text-xs text-[#1D4ED8] hover:text-blue-300 font-body underline">
                      Run scan now →
                    </button>
                  )}
                </div>
              ) : (
                <div className="divide-y divide-[#FFFFFF]">
                  {queue.map((item) => (
                    <div key={item.id} className="p-4">
                      <div className="flex items-start justify-between gap-3">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 mb-1 flex-wrap">
                            <span className="text-xs font-body font-bold px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400">
                              {item.company_name}
                            </span>
                            <span className="text-xs text-[#444] font-body">from</span>
                            <span className="text-xs text-[#666] font-body truncate max-w-[200px]">{item.source_article_title}</span>
                          </div>
                          <p className="text-sm font-body font-semibold text-white mb-1">{item.ai_draft_title}</p>
                          <p className="text-xs text-[#666] font-body line-clamp-2">{item.ai_draft_excerpt}</p>
                          <div className="flex items-center gap-3 mt-2">
                            <span className="text-xs text-[#444] font-body">{timeAgo(item.created_at)}</span>
                            {item.reminder_sent && (
                              <span className="text-xs text-green-500/70 font-body flex items-center gap-1">
                                <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                </svg>
                                Reminder sent
                              </span>
                            )}
                          </div>
                        </div>
                        {activeTab === 'queued' && (
                          <div className="flex flex-col gap-1.5 flex-shrink-0">
                            <button
                              onClick={() => handleAction(item.id, 'publish')}
                              disabled={actionLoading === item.id}
                              className="px-3 py-1.5 bg-green-500/10 hover:bg-green-500/20 text-green-400 text-xs font-body font-semibold rounded-md transition-colors disabled:opacity-50 flex items-center gap-1"
                            >
                              {actionLoading === item.id ? (
                                <div className="w-3 h-3 border border-green-400/30 border-t-green-400 rounded-full animate-spin" />
                              ) : (
                                <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                                </svg>
                              )}
                              Publish
                            </button>
                            <button
                              onClick={() => setExpandedItem(expandedItem === item.id ? null : item.id)}
                              className="px-3 py-1.5 bg-[#FFFFFF] hover:bg-[#222] text-[#888] text-xs font-body rounded-md transition-colors"
                            >
                              {expandedItem === item.id ? 'Hide' : 'Preview'}
                            </button>
                            <button
                              onClick={() => handleAction(item.id, 'dismiss')}
                              disabled={actionLoading === item.id}
                              className="px-3 py-1.5 bg-red-500/10 hover:bg-red-500/20 text-red-400 text-xs font-body rounded-md transition-colors disabled:opacity-50"
                            >
                              Dismiss
                            </button>
                          </div>
                        )}
                      </div>

                      {/* Expanded Draft Preview */}
                      {expandedItem === item.id && (
                        <div className="mt-4 bg-[#F8FAFC] border border-[#FFFFFF] rounded-lg p-4">
                          <p className="text-xs font-body font-bold text-[#555] uppercase tracking-widest mb-3">AI Draft Preview</p>
                          <h3 className="text-base font-display font-bold text-white mb-2">{item.ai_draft_title}</h3>
                          <p className="text-sm text-[#888] font-body italic mb-3">{item.ai_draft_excerpt}</p>
                          <div
                            className="text-sm text-[#aaa] font-body leading-relaxed prose prose-invert prose-sm max-w-none"
                            dangerouslySetInnerHTML={{ __html: item.ai_draft_content || '' }}
                          />
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Control Panel */}
          <div className="flex flex-col gap-4">

            {/* Auto-Pilot Toggle */}
            <div className={`bg-[#111] border rounded-lg p-5 transition-colors ${settings.autopilot_enabled ? 'border-green-500/40' : 'border-[#DCE6F2]'}`}>
              <div className="flex items-start justify-between gap-3 mb-3">
                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <svg className="w-4 h-4 text-[#1D4ED8]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                    </svg>
                    <h3 className="text-sm font-display font-bold text-white">Auto-Pilot</h3>
                  </div>
                  <p className="text-xs text-[#555] font-body leading-relaxed">
                    When enabled, AI-drafted company stories are automatically published without manual review.
                  </p>
                </div>
                <button
                  onClick={handleToggleAutopilot}
                  disabled={savingSettings}
                  className={`relative flex-shrink-0 w-11 h-6 rounded-full transition-colors duration-200 focus:outline-none disabled:opacity-50 ${
                    settings.autopilot_enabled ? 'bg-green-500' : 'bg-[#333]'
                  }`}
                  aria-label="Toggle Auto-Pilot"
                >
                  <span
                    className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform duration-200 ${
                      settings.autopilot_enabled ? 'translate-x-5' : 'translate-x-0'
                    }`}
                  />
                </button>
              </div>

              {settings.autopilot_enabled ? (
                <div className="flex items-center gap-2 bg-green-500/10 border border-green-500/20 rounded-md px-3 py-2">
                  <div className="w-2 h-2 rounded-full bg-green-400 animate-pulse flex-shrink-0" />
                  <p className="text-xs text-green-400 font-body font-semibold">Auto-Pilot is ON — stories publish automatically</p>
                </div>
              ) : (
                <div className="flex items-center gap-2 bg-[#FFFFFF] rounded-md px-3 py-2">
                  <div className="w-2 h-2 rounded-full bg-[#444] flex-shrink-0" />
                  <p className="text-xs text-[#666] font-body">Manual review required before publishing</p>
                </div>
              )}
            </div>

            {/* Reminder Settings */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
              <div className="flex items-center gap-2 mb-3">
                <svg className="w-4 h-4 text-[#888]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                <h3 className="text-sm font-display font-bold text-white">Reminder Email</h3>
              </div>
              <p className="text-xs text-[#555] font-body mb-2">New story suggestions are emailed to:</p>
              <div className="bg-[#F8FAFC] border border-[#FFFFFF] rounded-md px-3 py-2">
                <p className="text-xs text-[#1D4ED8] font-body font-mono break-all">{settings.reminder_email}</p>
              </div>
              <p className="text-xs text-[#444] font-body mt-2">Reminders are sent when Auto-Pilot is off and new companies are detected.</p>
            </div>

            {/* Last Scan Info */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
              <div className="flex items-center gap-2 mb-3">
                <svg className="w-4 h-4 text-[#888]" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
                  <circle cx="12" cy="12" r="10" /><path strokeLinecap="round" d="M12 6v6l4 2" />
                </svg>
                <h3 className="text-sm font-display font-bold text-white">Last Scan</h3>
              </div>
              {settings.last_scan_at ? (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <span className="text-xs text-[#555] font-body">Ran</span>
                    <span className="text-xs text-white font-body">{timeAgo(settings.last_scan_at)}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-xs text-[#555] font-body">Articles scanned</span>
                    <span className="text-xs text-white font-body">{settings.last_scan_articles_processed ?? 0}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-xs text-[#555] font-body">Companies found</span>
                    <span className="text-xs text-white font-body">{settings.last_scan_companies_found ?? 0}</span>
                  </div>
                </div>
              ) : (
                <p className="text-xs text-[#444] font-body">No scan has been run yet.</p>
              )}
            </div>

            {/* How It Works */}
            <div className="bg-[#111] border border-[#DCE6F2] rounded-lg p-5">
              <h3 className="text-xs font-body font-bold text-[#555] uppercase tracking-widest mb-3">How It Works</h3>
              <ol className="space-y-2">
                {[
                  'Scan published articles for company mentions',
                  'AI extracts company names from article content',
                  'AI drafts a story suggestion for each company',
                  'Stories queue for editor review (or auto-publish)',
                  'Email reminder sent to coverage contact',
                ].map((step, i) => (
                  <li key={i} className="flex items-start gap-2">
                    <span className="flex-shrink-0 w-4 h-4 rounded-full bg-[#FFFFFF] text-[#555] text-xs font-body font-bold flex items-center justify-center mt-0.5">
                      {i + 1}
                    </span>
                    <span className="text-xs text-[#666] font-body leading-relaxed">{step}</span>
                  </li>
                ))}
              </ol>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
