'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';

export default function OrgReportPage() {
  const params = useParams();
  const orgId = Number(params.id);
  const [report, setReport] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  function getToken() { return localStorage.getItem('adminToken'); }
  function headers() {
    const t = getToken();
    return { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) };
  }

  useEffect(() => { loadReport(); }, [orgId]);

  const base = API_BASE;

  async function loadReport() {
    try {
      const res = await fetch(`${base}/enterprise/organizations/${orgId}/report`, { headers: headers() });
      if (res.ok) setReport(await res.json());
    } catch {}
    setLoading(false);
  }

  if (loading) return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Skeleton className="h-8 w-48 mb-6" />
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        <Skeleton className="h-24 rounded-xl" />
        <Skeleton className="h-24 rounded-xl" />
        <Skeleton className="h-24 rounded-xl" />
        <Skeleton className="h-24 rounded-xl" />
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <Skeleton className="h-48 rounded-xl" />
        <Skeleton className="h-48 rounded-xl" />
      </div>
    </div>
  );

  if (!report) return <div className="text-center py-20 text-muted-foreground">报告加载失败</div>;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <Link href={`/admin/enterprise/${orgId}`} className="text-sm text-muted-foreground hover:text-brand-600 mb-4 inline-block">&larr; 返回组织详情</Link>

      <div className="mb-8">
        <h1 className="text-2xl font-bold text-foreground">{report.organization.name} - 学习报告</h1>
        <p className="text-muted-foreground mt-1">成员 {report.organization.memberCount} 人</p>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-8">
        {[
          { label: '总成员', value: report.summary.totalMembers, color: 'text-brand-600' },
          { label: '总课程', value: report.summary.totalCourses, color: 'text-purple-600' },
          { label: '已完成课时', value: report.summary.completedLessons, color: 'text-green-600' },
          { label: '完成率', value: `${report.summary.completionRate}%`, color: 'text-brand-600' },
        ].map(stat => (
          <div key={stat.label} className="bg-muted/50 rounded-xl p-6">
            <div className={`text-3xl font-bold ${stat.color}`}>{stat.value}</div>
            <div className="text-sm text-muted-foreground mt-1">{stat.label}</div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div>
          <h2 className="text-lg font-bold text-foreground mb-4">成员学习进度</h2>
          <div className="bg-card rounded-xl border border-border divide-y">
            {report.memberProgress?.map((mp: any) => (
              <div key={mp.user.id} className="flex items-center justify-between px-4 py-3">
                <div className="flex items-center gap-3">
                  <div className="w-8 h-8 rounded-full bg-brand-100 flex items-center justify-center text-brand-600 text-xs font-bold">
                    {mp.user.nickname?.[0] || 'U'}
                  </div>
                  <div className="text-sm font-medium">{mp.user.nickname || '用户'}</div>
                </div>
                <div className="text-sm text-muted-foreground">{mp.completedLessons} 课时完成</div>
              </div>
            ))}
            {(!report.memberProgress || report.memberProgress.length === 0) && (
              <div className="text-center py-8 text-muted-foreground text-sm">暂无数据</div>
            )}
          </div>
        </div>

        <div>
          <h2 className="text-lg font-bold text-foreground mb-4">已分配课程</h2>
          <div className="bg-card rounded-xl border border-border divide-y">
            {report.assignments?.map((a: any) => {
              const progress = report.summary.progressByCourse?.find((p: any) => p.courseId === a.courseId);
              return (
                <div key={a.id} className="px-4 py-3">
                  <div className="text-sm font-medium mb-2">{a.course?.title || '课程#' + a.courseId}</div>
                  {progress && (
                    <div className="flex items-center gap-3">
                      <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                        <div className="h-full bg-brand-500 rounded-full"
                          style={{ width: `${Math.min(100, (progress.completedLessons / Math.max(progress.totalUniqueLessons, 1)) * 100)}%` }} />
                      </div>
                      <span className="text-xs text-muted-foreground">{progress.completedLessons}/{progress.totalUniqueLessons}</span>
                    </div>
                  )}
                </div>
              );
            })}
            {(!report.assignments || report.assignments.length === 0) && (
              <div className="text-center py-8 text-muted-foreground text-sm">暂未分配课程</div>
            )}
          </div>
        </div>
      </div>

      <div className="mt-8 text-right">
        <button onClick={() => window.print()}
          className="px-4 py-2 bg-muted text-muted-foreground rounded-lg text-sm hover:bg-accent">
          导出报告 (打印)
        </button>
      </div>
    </div>
  );
}
