'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useT } from '@/i18n';
import { API_BASE } from '@/lib/config';
import { useAuth } from '@/lib/auth-context';
import { apiFetch, getToken } from '@/lib/auth';
import { Building2, Users, BarChart3, Plus, X, LogIn } from 'lucide-react';
import { toast } from 'sonner';

interface Org {
  id: number;
  name: string;
  description: string | null;
  contactName: string | null;
  memberCount: number;
  status: string;
  createdAt: string;
  members?: OrgMember[];
  _count?: { members: number; assignments: number };
}

interface OrgMember {
  id: number;
  userId: number;
  role: string;
  user: { id: number; nickname: string | null; email: string | null; phone: string | null; avatar: string | null };
}

interface OrgReport {
  organization: Org;
  totalMembers: number;
  totalCourses: number;
  completedLessons: number;
  completionRate: number;
  memberProgress: { userId: number; nickname: string; completed: number }[];
}

export default function EnterpriseDashboardPage() {
  const t = useT();
  const { isLoggedIn } = useAuth();
  const [orgs, setOrgs] = useState<Org[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedOrg, setSelectedOrg] = useState<Org | null>(null);
  const [orgMembers, setOrgMembers] = useState<OrgMember[]>([]);
  const [orgReport, setOrgReport] = useState<OrgReport | null>(null);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newOrgName, setNewOrgName] = useState('');
  const [newOrgDesc, setNewOrgDesc] = useState('');
  const [creating, setCreating] = useState(false);
  const [inviteUserId, setInviteUserId] = useState('');
  const [inviting, setInviting] = useState(false);
  const [activeTab, setActiveTab] = useState<'members' | 'report'>('members');

  useEffect(() => {
    if (!isLoggedIn) { setLoading(false); return; }
    loadOrgs();
  }, [isLoggedIn]);

  async function loadOrgs() {
    try {
      const res = await apiFetch('/enterprise/my');
      if (res.ok) {
        const data = await res.json();
        setOrgs(data || []);
      }
    } catch { /* ignore */ }
    setLoading(false);
  }

  async function selectOrg(org: Org) {
    setSelectedOrg(org);
    setActiveTab('members');
    try {
      const [detailRes, reportRes] = await Promise.all([
        apiFetch(`/enterprise/organizations/${org.id}`),
        apiFetch(`/enterprise/organizations/${org.id}/report`),
      ]);
      if (detailRes.ok) {
        const data = await detailRes.json();
        setOrgMembers(data.members || []);
      }
      if (reportRes.ok) {
        const data = await reportRes.json();
        setOrgReport(data);
      }
    } catch { toast.error("加载组织信息失败") }
  }

  async function createOrg() {
    if (!newOrgName.trim()) return;
    setCreating(true);
    try {
      const res = await apiFetch('/enterprise/organizations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: newOrgName.trim(), description: newOrgDesc.trim() || undefined }),
      });
      if (res.ok) {
        setShowCreateForm(false);
        setNewOrgName('');
        setNewOrgDesc('');
        loadOrgs();
      } else {
        const err = await res.json();
        toast.error(err.message || '创建失败');
      }
    } catch { toast.error("创建组织失败") }
    setCreating(false);
  }

  async function inviteMember() {
    if (!inviteUserId.trim() || !selectedOrg) return;
    setInviting(true);
    try {
      const res = await apiFetch(`/enterprise/organizations/${selectedOrg.id}/members`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: parseInt(inviteUserId) }),
      });
      if (res.ok) {
        setInviteUserId('');
        selectOrg(selectedOrg);
      } else {
        const err = await res.json();
        toast.error(err.message || '邀请失败');
      }
    } catch { toast.error("邀请失败") }
    setInviting(false);
  }

  async function removeMember(userId: number) {
    if (!selectedOrg || !confirm(t.enterprise.removeConfirm)) return;
    try {
      await apiFetch(`/enterprise/organizations/${selectedOrg.id}/members/${userId}`, {
        method: 'DELETE',
      });
      selectOrg(selectedOrg);
    } catch { toast.error("移除成员失败") }
  }

  if (!isLoggedIn) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-20 text-center">
        <Building2 className="h-12 w-12 text-brand-600 mx-auto mb-4" />
        <h1 className="text-2xl font-bold text-foreground mb-2">{t.enterprise.dashboard}</h1>
        <p className="text-muted-foreground mb-6">{t.enterprise.desc}</p>
        <Button asChild><Link href="/auth">{t.common.login}</Link></Button>
      </div>
    );
  }

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

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-foreground">{t.enterprise.dashboard}</h1>
          <p className="text-muted-foreground mt-1">{t.enterprise.desc}</p>
        </div>
        <Button onClick={() => setShowCreateForm(true)} className="flex items-center gap-2">
          <Plus className="h-4 w-4" /> {t.enterprise.createOrg}
        </Button>
      </div>

      {showCreateForm && (
        <div className="bg-card rounded-2xl border border-border p-6 mb-6">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-foreground">{t.enterprise.createOrg}</h2>
            <button onClick={() => setShowCreateForm(false)}><X className="h-5 w-5 text-muted-foreground" /></button>
          </div>
          <div className="space-y-3">
            <Input value={newOrgName} onChange={e => setNewOrgName(e.target.value)}
              placeholder={t.enterprise.orgName} />
            <Input value={newOrgDesc} onChange={e => setNewOrgDesc(e.target.value)}
              placeholder={t.enterprise.orgDesc} />
            <Button onClick={createOrg} disabled={creating || !newOrgName.trim()}>
              {creating ? t.common.loading : t.enterprise.createOrg}
            </Button>
          </div>
        </div>
      )}

      {orgs.length === 0 ? (
        <div className="bg-card rounded-2xl border border-border p-12 text-center">
          <Building2 className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
          <h2 className="text-lg font-semibold text-foreground mb-2">{t.enterprise.noOrg}</h2>
          <p className="text-sm text-muted-foreground mb-6">{t.enterprise.createOrgHint}</p>
          <Button onClick={() => setShowCreateForm(true)}>{t.enterprise.createOrg}</Button>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div className="lg:col-span-1 space-y-3">
            <h2 className="font-semibold text-foreground mb-2">{t.enterprise.myTeam}</h2>
            {orgs.map(org => (
              <button key={org.id} onClick={() => selectOrg(org)}
                className={`w-full text-left bg-card rounded-xl border p-4 transition-all hover:shadow-sm ${
                  selectedOrg?.id === org.id ? 'border-brand-600' : 'border-border'
                }`}>
                <div className="font-medium text-foreground text-sm">{org.name}</div>
                <div className="text-xs text-muted-foreground mt-1">
                  {t.enterprise.memberCount.replace('{n}', String(org.memberCount || org._count?.members || 0))}
                </div>
              </button>
            ))}
          </div>

          <div className="lg:col-span-2">
            {selectedOrg ? (
              <div>
                <div className="flex items-center gap-2 mb-4">
                  <button onClick={() => setActiveTab('members')}
                    className={`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${
                      activeTab === 'members' ? 'bg-brand-600 text-white border-brand-600' : 'bg-card text-muted-foreground border-border'
                    }`}>
                    <Users className="h-3.5 w-3.5 inline mr-1" />{t.enterprise.members}
                  </button>
                  <button onClick={() => setActiveTab('report')}
                    className={`px-3 py-1.5 rounded-xl text-xs font-medium border transition-colors ${
                      activeTab === 'report' ? 'bg-brand-600 text-white border-brand-600' : 'bg-card text-muted-foreground border-border'
                    }`}>
                    <BarChart3 className="h-3.5 w-3.5 inline mr-1" />{t.enterprise.usageReport}
                  </button>
                </div>

                {activeTab === 'members' && (
                  <div className="bg-card rounded-2xl border border-border p-6">
                    <div className="flex items-center justify-between mb-4">
                      <h3 className="font-semibold text-foreground">{t.enterprise.members} ({orgMembers.length})</h3>
                    </div>

                    <div className="flex gap-2 mb-4">
                      <Input value={inviteUserId} onChange={e => setInviteUserId(e.target.value)}
                        placeholder={t.enterprise.memberId} className="w-40" type="number" />
                      <Button onClick={inviteMember} disabled={inviting || !inviteUserId.trim()} size="sm">
                        {inviting ? t.common.loading : t.enterprise.invite}
                      </Button>
                    </div>

                    {orgMembers.length === 0 ? (
                      <p className="text-sm text-muted-foreground text-center py-8">{t.enterprise.noMembers}</p>
                    ) : (
                      <div className="space-y-2">
                        {orgMembers.map(m => (
                          <div key={m.id} className="flex items-center justify-between p-3 bg-muted/30 rounded-xl">
                            <div className="flex items-center gap-3">
                              <div className="w-8 h-8 bg-muted rounded-full flex items-center justify-center text-xs font-medium text-foreground">
                                {m.user.nickname?.[0] || '?'}
                              </div>
                              <div>
                                <div className="text-sm font-medium text-foreground">{m.user.nickname || `用户 ${m.userId}`}</div>
                                <div className="text-xs text-muted-foreground">
                                  {m.user.email || m.user.phone || `#${m.userId}`}
                                  {m.role === 'ADMIN' && <span className="ml-2 text-brand-600">管理员</span>}
                                </div>
                              </div>
                            </div>
                            {m.role !== 'ADMIN' && (
                              <button onClick={() => removeMember(m.userId)}
                                className="text-xs text-red-500 hover:text-red-700">移除</button>
                            )}
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                )}

                {activeTab === 'report' && orgReport && (
                  <div className="space-y-4">
                    <div className="grid grid-cols-3 gap-4">
                      {[
                        { label: t.enterprise.totalMembers, value: orgReport.totalMembers },
                        { label: t.enterprise.totalUsage, value: orgReport.completedLessons },
                        { label: t.enterprise.completionRate, value: `${Math.round(orgReport.completionRate)}%` },
                      ].map((s, i) => (
                        <div key={i} className="bg-card rounded-xl border border-border p-4 text-center">
                          <div className="text-2xl font-bold text-foreground">{s.value}</div>
                          <div className="text-xs text-muted-foreground mt-1">{s.label}</div>
                        </div>
                      ))}
                    </div>

                    {orgReport.memberProgress.length > 0 && (
                      <div className="bg-card rounded-2xl border border-border p-6">
                        <h3 className="font-semibold text-foreground mb-3">{t.enterprise.members} 进度</h3>
                        <div className="space-y-3">
                          {orgReport.memberProgress.map((mp, i) => (
                            <div key={i} className="flex items-center gap-3">
                              <span className="text-sm text-foreground w-24 truncate">{mp.nickname || `用户 ${mp.userId}`}</span>
                              <div className="flex-1 bg-muted rounded-full h-2">
                                <div className="bg-brand-600 h-2 rounded-full" style={{ width: `${Math.min(100, mp.completed * 10)}%` }} />
                              </div>
                              <span className="text-xs text-muted-foreground">{mp.completed} 课时</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ) : (
              <div className="bg-card rounded-2xl border border-border p-12 text-center">
                <p className="text-muted-foreground">{t.enterprise.selectOrg || '选择一个团队查看详情'}</p>
              </div>
            )}
          </div>
        </div>
      )}

      <div className="mt-12 bg-card rounded-2xl border border-border p-8">
        <div className="text-center max-w-2xl mx-auto">
          <h2 className="text-xl font-bold text-foreground mb-3">{t.enterprise.pricingTitle}</h2>
          <p className="text-muted-foreground mb-6">{t.enterprise.pricingDesc}</p>
          <div className="flex items-center justify-center gap-4">
            <div className="text-center">
              <div className="text-3xl font-bold text-foreground">{t.enterprise.pricingBizPrice}</div>
              <div className="text-xs text-muted-foreground">{t.enterprise.pricingBizPerUser}</div>
            </div>
            <div className="h-12 w-px bg-border" />
            <div className="text-left text-sm text-muted-foreground">
              <div>✓ {t.enterprise.pricingBizFeature1}</div>
              <div>✓ {t.enterprise.pricingBizFeature3}</div>
              <div>✓ {t.enterprise.pricingBizFeature4}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
