'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 OrgDetailPage() {
  const params = useParams();
  const orgId = Number(params.id);
  const [org, setOrg] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [showAddMember, setShowAddMember] = useState(false);
  const [showAssignCourse, setShowAssignCourse] = useState(false);
  const [showEdit, setShowEdit] = useState(false);
  const [memberUserId, setMemberUserId] = useState('');
  const [courseId, setCourseId] = useState('');
  const [courseDeadline, setCourseDeadline] = useState('');
  const [courses, setCourses] = useState<any[]>([]);
  const [editForm, setEditForm] = useState({ name: '', description: '', contactName: '', contactPhone: '' });

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

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

  const base = API_BASE;

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

  async function loadCourses() {
    try {
      const res = await fetch(`${base}/courses`, { headers: headers() });
      if (res.ok) {
        const data = await res.json();
        setCourses(data.items || []);
      }
    } catch {}
  }

  async function addMember() {
    const uid = Number(memberUserId);
    if (!uid) return;
    try {
      const res = await fetch(`${base}/enterprise/organizations/${orgId}/members`, {
        method: 'POST', headers: headers(),
        body: JSON.stringify({ userId: uid }),
      });
      if (res.ok) {
        setShowAddMember(false);
        setMemberUserId('');
        loadOrg();
      }
    } catch {}
  }

  async function removeMember(userId: number) {
    try {
      await fetch(`${base}/enterprise/organizations/${orgId}/members/${userId}`, {
        method: 'DELETE', headers: headers(),
      });
      loadOrg();
    } catch {}
  }

  async function assignCourse() {
    const cid = Number(courseId);
    if (!cid) return;
    try {
      const body: any = { courseId: cid };
      if (courseDeadline) body.deadline = courseDeadline;
      const res = await fetch(`${base}/enterprise/organizations/${orgId}/assignments`, {
        method: 'POST', headers: headers(),
        body: JSON.stringify(body),
      });
      if (res.ok) {
        setShowAssignCourse(false);
        setCourseId('');
        setCourseDeadline('');
        loadOrg();
      }
    } catch {}
  }

  async function updateOrg() {
    try {
      const res = await fetch(`${base}/enterprise/organizations/${orgId}`, {
        method: 'PUT', headers: headers(),
        body: JSON.stringify(editForm),
      });
      if (res.ok) {
        setShowEdit(false);
        loadOrg();
      }
    } catch {}
  }

  async function removeAssignment(courseId: number) {
    try {
      await fetch(`${base}/enterprise/organizations/${orgId}/assignments/${courseId}`, {
        method: 'DELETE', headers: headers(),
      });
      loadOrg();
    } catch {}
  }

  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" />
      <Skeleton className="h-24 w-full rounded-xl mb-6" />
      <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 (!org) 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">
      <div className="bg-card rounded-xl border border-border p-6 mb-8">
        <Link href="/admin/enterprise" className="text-sm text-muted-foreground hover:text-brand-600 mb-4 inline-block">&larr; 返回企业列表</Link>
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground mb-2">{org.name}</h1>
            {org.description && <p className="text-muted-foreground mb-4">{org.description}</p>}
            <div className="flex gap-6 text-sm text-muted-foreground">
              <span>联系人: {org.contactName || '-'}</span>
              <span>电话: {org.contactPhone || '-'}</span>
              <span>成员: {org._count?.members || 0}</span>
              <span>课程: {org._count?.assignments || 0}</span>
            </div>
          </div>
          <button onClick={() => {
            setEditForm({ name: org.name, description: org.description || '', contactName: org.contactName || '', contactPhone: org.contactPhone || '' });
            setShowEdit(!showEdit);
          }} className="text-sm px-3 py-1.5 border border-border rounded-lg hover:bg-accent shrink-0 ml-4">
            {showEdit ? '取消' : '编辑'}
          </button>
        </div>
        {showEdit && (
          <div className="mt-4 pt-4 border-t border-border space-y-3">
            <input value={editForm.name} onChange={e => setEditForm(f => ({ ...f, name: e.target.value }))}
              placeholder="组织名称" className="w-full px-3 py-2 border border-input rounded-lg text-sm" />
            <input value={editForm.description} onChange={e => setEditForm(f => ({ ...f, description: e.target.value }))}
              placeholder="组织描述" className="w-full px-3 py-2 border border-input rounded-lg text-sm" />
            <div className="flex gap-2">
              <input value={editForm.contactName} onChange={e => setEditForm(f => ({ ...f, contactName: e.target.value }))}
                placeholder="联系人" className="flex-1 px-3 py-2 border border-input rounded-lg text-sm" />
              <input value={editForm.contactPhone} onChange={e => setEditForm(f => ({ ...f, contactPhone: e.target.value }))}
                placeholder="联系电话" className="flex-1 px-3 py-2 border border-input rounded-lg text-sm" />
            </div>
            <button onClick={updateOrg} className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">保存修改</button>
          </div>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-foreground">成员管理</h2>
            <button onClick={() => setShowAddMember(!showAddMember)}
              className="text-sm px-3 py-1.5 bg-brand-600 text-white rounded-lg hover:bg-brand-700">
              {showAddMember ? '取消' : '+ 添加成员'}
            </button>
          </div>
          {showAddMember && (
            <div className="flex gap-2 mb-4">
              <input value={memberUserId} onChange={e => setMemberUserId(e.target.value)}
                placeholder="用户ID" type="number" className="flex-1 px-3 py-2 border border-input rounded-lg text-sm" />
              <button onClick={addMember} className="px-3 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">确认</button>
            </div>
          )}
          <div className="bg-card rounded-xl border border-border divide-y">
            {org.members?.map((m: any) => (
              <div key={m.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">
                    {m.user?.nickname?.[0] || 'U'}
                  </div>
                  <div>
                    <div className="text-sm font-medium">{m.user?.nickname || '用户'}</div>
                    <div className="text-xs text-muted-foreground">{m.user?.email || m.user?.phone || 'ID: ' + m.userId}</div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`text-xs px-2 py-0.5 rounded ${m.role === 'ADMIN' ? 'bg-purple-50 text-purple-600' : 'bg-muted text-muted-foreground'}`}>
                    {m.role === 'ADMIN' ? '管理员' : '成员'}
                  </span>
                  {m.role !== 'ADMIN' && (
                    <button onClick={() => removeMember(m.userId)} className="text-xs text-red-500 hover:text-red-600">移除</button>
                  )}
                </div>
              </div>
            ))}
            {(!org.members || org.members.length === 0) && (
              <div className="text-center py-8 text-muted-foreground text-sm">暂无成员</div>
            )}
          </div>
        </div>

        <div>
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-bold text-foreground">课程分配</h2>
            <button onClick={() => setShowAssignCourse(!showAssignCourse)}
              className="text-sm px-3 py-1.5 bg-brand-600 text-white rounded-lg hover:bg-brand-700">
              {showAssignCourse ? '取消' : '+ 分配课程'}
            </button>
          </div>
          {showAssignCourse && (
            <div className="flex flex-col gap-2 mb-4">
              <div className="flex gap-2">
                <select value={courseId} onChange={e => setCourseId(e.target.value)}
                  className="flex-1 px-3 py-2 border border-input rounded-lg text-sm">
                  <option value="">选择课程</option>
                  {courses.map((c: any) => (
                    <option key={c.id} value={c.id}>{c.title}</option>
                  ))}
                </select>
                <button onClick={assignCourse} className="px-3 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">确认</button>
              </div>
              <input type="date" value={courseDeadline} onChange={e => setCourseDeadline(e.target.value)}
                className="px-3 py-2 border border-input rounded-lg text-sm" />
            </div>
          )}
          <div className="bg-card rounded-xl border border-border divide-y">
            {org.assignments?.map((a: any) => (
                  <div key={a.id} className="flex items-center justify-between px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="text-sm font-medium">{a.course?.title || '课程#' + a.courseId}</div>
                      {a.deadline && <span className="text-xs text-muted-foreground">截止: {new Date(a.deadline).toLocaleDateString()}</span>}
                    </div>
                    <button onClick={() => removeAssignment(a.courseId)} className="text-xs text-red-500 hover:text-red-600">移除</button>
                  </div>
            ))}
            {(!org.assignments || org.assignments.length === 0) && (
              <div className="text-center py-8 text-muted-foreground text-sm">暂未分配课程</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
