// frontend/src/pages/Dashboard.jsx
import { useState, useEffect, useCallback } from 'react';
import { 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, StatusBadge, ProgressBar, EmptyState, Spinner } from '../components/ui/index.jsx';
import { Zap, FileText, Newspaper, Video, ArrowRight, Clock, CheckCircle2, XCircle } from 'lucide-react';
import toast from 'react-hot-toast';
import { formatDistanceToNow, format } from 'date-fns';
import OnboardingWizard from '../components/onboarding/OnboardingWizard.jsx';

export default function Dashboard() {
  const { user } = useAuth();
  const t = useT(user?.locale);
  const [stats, setStats] = useState(null);
  const [pipelineStatus, setPipelineStatus] = useState(null);
  const [recentContent, setRecentContent] = useState([]);
  const [runLoading, setRunLoading] = useState(false);
  const [showOnboarding, setShowOnboarding] = useState(!user?.onboardingCompleted);

  const completeOnboarding = async () => {
    try { await api.post('/auth/complete-onboarding'); } catch {}
    setShowOnboarding(false);
  };
  const [jobId, setJobId] = useState(null);
  const [jobProgress, setJobProgress] = useState(0);

  const fetchData = useCallback(async () => {
    try {
      const [statsRes, statusRes, contentRes] = await Promise.all([
        api.get('/content/stats/summary'),
        api.get('/pipeline/status'),
        api.get('/content?limit=5'),
      ]);
      const statsMap = {};
      for (const row of statsRes.data) statsMap[row.content_type] = parseInt(row.count);
      setStats(statsMap);
      setPipelineStatus(statusRes.data);
      setRecentContent(contentRes.data.items || []);
    } catch (err) {
      console.error(err);
    }
  }, []);

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

  // Poll job progress when running
  useEffect(() => {
    if (!jobId) return;
    const interval = setInterval(async () => {
      try {
        const { data } = await api.get(`/pipeline/job/${jobId}`);
        setJobProgress(data.progress || 0);
        if (data.state === 'completed' || data.state === 'failed') {
          clearInterval(interval);
          setJobId(null);
          setRunLoading(false);
          setJobProgress(0);
          fetchData();
          if (data.state === 'completed') toast.success('Pipeline completed! 🎉');
          else toast.error('Pipeline failed. Check history.');
        }
      } catch {}
    }, 2000);
    return () => clearInterval(interval);
  }, [jobId, fetchData]);

  const runPipeline = async () => {
    setRunLoading(true);
    try {
      const { data } = await api.post('/pipeline/run');
      setJobId(data.jobId);
      toast.success('Pipeline started!');
    } catch (err) {
      setRunLoading(false);
      const msg = err.response?.data?.message || err.response?.data?.error || 'Failed to start pipeline';
      toast.error(msg);
    }
  };

  const isRunning = pipelineStatus?.status === 'running' || pipelineStatus?.status === 'queued' || runLoading;

  return (
    <>
      {showOnboarding && <OnboardingWizard onComplete={completeOnboarding} />}
      <div className="space-y-8">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-semibold text-gray-900">
            {t('dashboard.welcome')}, {user?.fullName?.split(' ')[0]} 👋
          </h1>
          <p className="text-gray-500 mt-1 text-sm">
            {format(new Date(), 'EEEE, MMMM d')} — {user?.planId} plan
          </p>
        </div>
        <Button
          onClick={runPipeline}
          loading={isRunning}
          size="lg"
          className="shadow-sm"
        >
          <Zap size={16} />
          {isRunning ? t('dashboard.runningNow') : t('dashboard.runPipeline')}
        </Button>
      </div>

      {/* Pipeline progress */}
      {isRunning && jobId && (
        <Card className="p-4 border-brand-200 bg-brand-50">
          <div className="flex items-center justify-between mb-2">
            <span className="text-sm font-medium text-brand-700">Running agents…</span>
            <span className="text-sm text-brand-600">{Math.round(jobProgress)}%</span>
          </div>
          <ProgressBar value={jobProgress} />
          <p className="text-xs text-brand-500 mt-2">Your content is being generated. This takes 3–8 minutes.</p>
        </Card>
      )}

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { icon: Video, label: t('dashboard.scriptsGenerated'), key: 'script', color: 'text-purple-500' },
          { icon: Zap, label: t('dashboard.postsGenerated'), key: 'post', color: 'text-blue-500' },
          { icon: Newspaper, label: t('dashboard.blogsGenerated'), key: 'blog', color: 'text-emerald-500' },
          { icon: FileText, label: t('dashboard.totalRuns'), key: '_runs', color: 'text-amber-500' },
        ].map(({ icon: Icon, label, key, color }) => (
          <Card key={key} className="p-5">
            <div className={`w-9 h-9 rounded-lg bg-gray-50 flex items-center justify-center mb-3`}>
              <Icon size={18} className={color} />
            </div>
            <p className="text-2xl font-semibold text-gray-900">
              {stats ? (stats[key] || 0) : <span className="text-gray-300">—</span>}
            </p>
            <p className="text-xs text-gray-500 mt-0.5">{label}</p>
          </Card>
        ))}
      </div>

      {/* Pipeline status + Recent content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Pipeline status */}
        <Card className="p-5">
          <h2 className="text-sm font-semibold text-gray-900 mb-4">{t('dashboard.pipelineStatus')}</h2>
          {pipelineStatus && pipelineStatus.status !== 'never_run' ? (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('dashboard.lastRun')}</span>
                <StatusBadge status={pipelineStatus.status} />
              </div>
              {pipelineStatus.started_at && (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500">Time</span>
                  <span className="text-sm text-gray-700">
                    {formatDistanceToNow(new Date(pipelineStatus.started_at), { addSuffix: true })}
                  </span>
                </div>
              )}
              {pipelineStatus.scripts_count > 0 && (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-500">Scripts</span>
                  <span className="text-sm font-medium text-gray-900">{pipelineStatus.scripts_count}</span>
                </div>
              )}
              {pipelineStatus.error_message && (
                <div className="mt-2 p-2 bg-red-50 rounded-lg">
                  <p className="text-xs text-red-600">{pipelineStatus.error_message}</p>
                </div>
              )}
            </div>
          ) : (
            <p className="text-sm text-gray-400">{t('dashboard.never')}</p>
          )}
          <Link to="/dashboard/pipeline" className="mt-4 flex items-center gap-1 text-xs text-brand-600 hover:text-brand-700 font-medium">
            View history <ArrowRight size={12} />
          </Link>
        </Card>

        {/* Recent content */}
        <Card className="lg:col-span-2 p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-gray-900">{t('dashboard.recentContent')}</h2>
            <Link to="/dashboard/content" className="text-xs text-brand-600 hover:text-brand-700 font-medium flex items-center gap-1">
              {t('dashboard.viewAll')} <ArrowRight size={12} />
            </Link>
          </div>

          {recentContent.length === 0 ? (
            <EmptyState
              icon={FileText}
              title={t('dashboard.noContent')}
              description=""
            />
          ) : (
            <div className="space-y-2">
              {recentContent.map(item => (
                <Link
                  key={item.id}
                  to={`/dashboard/content/${item.id}`}
                  className="flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors group"
                >
                  <div className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <ContentTypeIcon type={item.content_type} />
                  </div>
                  <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">{formatDistanceToNow(new Date(item.created_at), { addSuffix: true })}</p>
                  </div>
                  <ArrowRight size={14} className="text-gray-300 group-hover:text-gray-500 transition-colors" />
                </Link>
              ))}
            </div>
          )}
        </Card>
      </div>
    </div>
    </>
  );
}

function ContentTypeIcon({ type }) {
  const icons = {
    script: '🎬', post: '𝕏', blog: '📰', newsletter: '📧',
    thumbnail: '🖼️', clip: '✂️', intel: '🔍', outreach: '🤝', performance: '📊'
  };
  return <span className="text-base">{icons[type] || '📄'}</span>;
}
