'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '@/lib/auth';
import { Skeleton } from '@/components/ui/skeleton';
import { useT } from '@/i18n';

interface Task { label: string; action: string; keyword: string }
interface StageLink { title: string; url: string }
interface Stage { id: string; title: string; icon: string; description: string; tasks: Task[]; links: StageLink[]; completedCount: number; totalTasks: number; progress: number; unlocked: boolean }

export default function LearningPathPage() {
  const t = useT();
  const [stages, setStages] = useState<Stage[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadPath() {
    try { const res = await apiFetch('/learning/path'); if (res.ok) setStages(await res.json()); } catch {}
    setLoading(false);
  }

  if (loading) return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-2" /><Skeleton className="h-5 w-64 mb-8" />
      {[1,2,3,4].map(i => <Skeleton key={i} className="h-40 w-full rounded-xl mb-4" />)}
    </div>
  );

  const totalProgress = stages.length ? Math.round(stages.reduce((s, st) => s + st.progress, 0) / stages.length) : 0;
  const totalCompleted = stages.reduce((s, st) => s + st.completedCount, 0);
  const totalTasks = stages.reduce((s, st) => s + st.totalTasks, 0);

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="mb-8">
        <Link href="/my" className="text-sm text-muted-foreground hover:text-brand-600 mb-2 inline-block">&larr; {t.path.back}</Link>
        <h1 className="text-3xl font-bold text-foreground">{t.learning.path}</h1>
        <p className="mt-2 text-muted-foreground">{t.learning.pathDesc}</p>
      </div>

      <div className="bg-card rounded-2xl border border-border p-6 mb-8">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-medium text-foreground">{t.path.totalProgress}</span>
          <span className="text-sm text-muted-foreground">{t.path.taskCount.replace('{completed}', String(totalCompleted)).replace('{total}', String(totalTasks))}</span>
        </div>
        <div className="w-full bg-muted rounded-full h-3">
          <div className="bg-brand-600 h-3 rounded-full transition-all" style={{ width: `${totalProgress}%` }} />
        </div>
      </div>

      <div className="relative">
        <div className="absolute left-8 top-0 bottom-0 w-0.5 bg-muted hidden md:block" />
        <div className="space-y-8">
          {stages.map((stage, index) => (
            <div key={stage.id} className="relative md:pl-20">
              <div className="hidden md:flex absolute left-0 top-0 w-16 items-center justify-center">
                <div className={`w-12 h-12 rounded-full flex items-center justify-center text-xl border-2 z-10 bg-card ${stage.progress === 100 ? 'border-green-500' : 'border-brand-600'}`}>
                  {stage.progress === 100 ? '✅' : stage.icon}
                </div>
              </div>
              <div className="bg-card rounded-2xl border border-border p-6">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <span className="md:hidden text-xl">{stage.progress === 100 ? '✅' : stage.icon}</span>
                      <h2 className="text-lg font-semibold text-foreground">{stage.title}</h2>
                    </div>
                    <p className="text-sm text-muted-foreground">{stage.description}</p>
                  </div>
                  <span className="text-xs text-muted-foreground tabular-nums shrink-0">{stage.completedCount}/{stage.totalTasks}</span>
                </div>
                <div className="w-full bg-muted rounded-full h-1.5 mb-4">
                  <div className={`h-1.5 rounded-full transition-all ${stage.progress === 100 ? 'bg-green-500' : 'bg-brand-600'}`} style={{ width: `${stage.progress}%` }} />
                </div>
                <div className="space-y-1.5 mb-4">
                  {stage.tasks.map((task, ti) => {
                    const done = ti < stage.completedCount;
                    return (
                      <div key={ti} className="flex items-center gap-2 text-sm">
                        <span className={`w-4 h-4 rounded-full border flex items-center justify-center shrink-0 ${done ? 'bg-green-500 border-green-500 text-white' : 'border-muted-foreground'}`}>
                          {done && <span className="text-[10px]">✓</span>}
                        </span>
                        <span className={done ? 'text-muted-foreground line-through' : 'text-foreground'}>{task.label}</span>
                        <span className="text-xs text-muted-foreground/60">— {task.action}</span>
                      </div>
                    );
                  })}
                </div>
                <div className="flex flex-wrap gap-2">
                  {stage.links.map((link, li) => (
                    <Link key={li} href={link.url} className="text-xs px-3 py-1.5 rounded-lg bg-brand-600 text-white hover:bg-brand-700 transition-colors">{link.title}</Link>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
