'use client';

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

interface Organization {
  id: number; name: string; description?: string;
  contactName?: string; contactPhone?: string;
  status: string; memberCount: number;
  _count: { members: number; assignments: number };
  createdAt: string;
}

export default function EnterprisePage() {
  const router = useRouter();
  const [orgs, setOrgs] = useState<Organization[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [form, setForm] = useState({ name: '', description: '', contactName: '', contactPhone: '' });

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

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

  async function loadOrgs() {
    try {
      const base = API_BASE;
      const res = await fetch(`${base}/enterprise/organizations`, { headers: headers() });
      if (res.ok) {
        const data = await res.json();
        setOrgs(data.items || []);
      }
    } catch {}
    setLoading(false);
  }

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    try {
      const base = API_BASE;
      const res = await fetch(`${base}/enterprise/organizations`, {
        method: 'POST', headers: headers(),
        body: JSON.stringify(form),
      });
      if (res.ok) {
        setShowCreate(false);
        setForm({ name: '', description: '', contactName: '', contactPhone: '' });
        loadOrgs();
      }
    } catch {}
  }

  if (loading) return (
    <div className="p-6">
      <div className="space-y-4">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-10 w-full" />
        <Skeleton className="h-10 w-full" />
        <Skeleton className="h-10 w-3/4" />
      </div>
    </div>
  );

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-foreground">企业版管理</h1>
          <p className="mt-1 text-sm text-muted-foreground">管理企业组织、成员和学习进度</p>
        </div>
        <button onClick={() => setShowCreate(!showCreate)}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">
          {showCreate ? '取消' : '+ 创建组织'}
        </button>
      </div>

      {showCreate && (
        <form onSubmit={handleCreate} className="bg-card rounded-xl border border-border p-6 mb-6">
          <h3 className="text-lg font-semibold mb-4">创建新组织</h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })}
              placeholder="组织名称 *" required className="px-3 py-2 border border-border rounded-lg text-sm" />
            <input value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })}
              placeholder="联系人" className="px-3 py-2 border border-border rounded-lg text-sm" />
            <input value={form.contactPhone} onChange={e => setForm({ ...form, contactPhone: e.target.value })}
              placeholder="联系电话" className="px-3 py-2 border border-border rounded-lg text-sm" />
            <input value={form.description} onChange={e => setForm({ ...form, description: e.target.value })}
              placeholder="描述" className="px-3 py-2 border border-border rounded-lg text-sm" />
          </div>
          <button type="submit" className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">创建</button>
        </form>
      )}

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <table className="w-full">
          <thead>
            <tr className="border-b border-border bg-muted/50">
              <th className="text-left px-6 py-3 text-sm font-medium text-muted-foreground">名称</th>
              <th className="text-left px-6 py-3 text-sm font-medium text-muted-foreground">联系人</th>
              <th className="text-center px-6 py-3 text-sm font-medium text-muted-foreground">成员</th>
              <th className="text-center px-6 py-3 text-sm font-medium text-muted-foreground">课程</th>
              <th className="text-center px-6 py-3 text-sm font-medium text-muted-foreground">状态</th>
              <th className="text-right px-6 py-3 text-sm font-medium text-muted-foreground">操作</th>
            </tr>
          </thead>
          <tbody>
            {orgs.map(org => (
              <tr key={org.id} className="border-b border-border hover:bg-accent/50">
                <td className="px-6 py-4">
                  <div className="font-medium text-foreground">{org.name}</div>
                  {org.description && <div className="text-xs text-muted-foreground mt-0.5">{org.description}</div>}
                </td>
                <td className="px-6 py-4 text-sm text-muted-foreground">
                  {org.contactName || '-'}<br />
                  {org.contactPhone && <span className="text-xs text-muted-foreground">{org.contactPhone}</span>}
                </td>
                <td className="px-6 py-4 text-center text-sm">{org._count?.members || 0}</td>
                <td className="px-6 py-4 text-center text-sm">{org._count?.assignments || 0}</td>
                <td className="px-6 py-4 text-center">
                  <span className={`text-xs px-2 py-0.5 rounded ${org.status === 'ACTIVE' ? 'bg-green-50 text-green-600' : 'bg-muted text-muted-foreground'}`}>
                    {org.status === 'ACTIVE' ? '启用' : '停用'}
                  </span>
                </td>
                <td className="px-6 py-4 text-right">
                  <Link href={`/admin/enterprise/${org.id}`}
                    className="text-sm text-brand-600 hover:text-brand-700 mr-4">详情</Link>
                  <Link href={`/admin/enterprise/${org.id}/report`}
                    className="text-sm text-brand-600 hover:text-brand-700">报告</Link>
                </td>
              </tr>
            ))}
            {orgs.length === 0 && (
              <tr><td colSpan={6} className="text-center py-12 text-muted-foreground">暂无组织</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
