import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, Ban, RotateCcw, KeyRound, Save, FolderKanban } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import FieldList from '@/components/workshop/FieldList';
import { accountService } from '@/services/accountService';
import { useAccount } from '@/lib/AccountContext';
import { ROLES, PERMISSION_PRESETS, resolvePermissions } from '@/config/permissions';

export default function AdminUserDetail() {
  const { userId } = useParams();
  const { account: me } = useAccount();
  const nav = useNavigate();
  const [account, setAccount] = useState(null);
  const [projects, setProjects] = useState(null);
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState({});

  const load = () => accountService.get(userId).then(setAccount);
  useEffect(() => { load(); }, [userId]);

  useEffect(() => {
    if (account) {
      setForm({ role: account.role, permission_preset: account.permission_preset });
      if (account.assigned_project_uuids?.length) {
        import('@/services/serviceConfig').then(({ adapters }) =>
          Promise.all(account.assigned_project_uuids.map(u => adapters.database.filter('CoverProject', { uuid: u }).then(r => r[0])))
        ).then(ps => setProjects(ps.filter(Boolean)));
      } else setProjects([]);
    }
  }, [account]);

  if (!account) return <LoadingPanel label="Loading account" />;

  const isLastOwner = account.role === 'owner_admin' && account.account_status === 'Active';
  const canManage = me?.role === 'owner_admin' || (me?.role === 'admin' && account.role !== 'owner_admin');
  const save = async () => {
    await accountService.update(account, { role: form.role, permission_preset: form.permission_preset }, me?.display_name);
    setEditing(false); load();
  };

  const rows = [
    ['Email', account.email], ['Display name', account.display_name], ['Role', ROLES.find(r => r.key === account.role)?.label],
    ['Status', account.account_status], ['Permission preset', PERMISSION_PRESETS[account.permission_preset]?.label || account.permission_preset],
    ['Linked customer', account.customer_number || '—'], ['Builder title', account.builder_title || '—'],
    ['Skills', (account.skills || []).join(', ') || '—'], ['Assigned projects', (account.assigned_project_uuids || []).length],
    ['Last login', account.last_login ? new Date(account.last_login).toLocaleString() : '—'],
    ['Email verified', account.email_verified ? 'Yes' : 'No'], ['Invited by', account.invited_by || 'Self-registered'],
    ['Created by', account.created_by_name], ['Suspension reason', account.suspension_reason || '—'],
  ];

  return (
    <>
      <Link to="/admin/users" className="mb-4 inline-flex items-center gap-1 text-sm text-slate-400 hover:text-violet-300"><ArrowLeft className="h-4 w-4" />Back to users</Link>
      <PageHeader eyebrow="Account" title={account.display_name || account.email} description={account.email}
        action={canManage ? <div className="flex gap-2">
          {!editing ? <button className="btn-secondary" onClick={() => setEditing(true)}><Save />Edit Role</button> :
            <button className="btn-primary" onClick={save}><Save />Save</button>}
          {account.account_status === 'Active' && !isLastOwner && <button className="btn-secondary" onClick={() => accountService.suspend(account, 'Suspended by admin', me?.display_name).then(load)}><Ban />Suspend</button>}
          {account.account_status === 'Suspended' && <button className="btn-secondary" onClick={() => accountService.reactivate(account, me?.display_name).then(load)}><RotateCcw />Reactivate</button>}
          <button className="btn-secondary" onClick={() => accountService.revokeSessions(account, me?.display_name).then(load)}><KeyRound />Revoke Sessions</button>
        </div> : null} />

      {isLastOwner && <div className="mb-4 rounded-lg border border-amber-400/30 bg-amber-400/10 p-3 text-xs text-amber-200">This is the last active Owner Admin — it cannot be suspended, archived or stripped of Owner Admin authority.</div>}

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="panel p-5 lg:col-span-2">
          <h2 className="section-title">Account Identity</h2>
          {editing ? (
            <div className="grid gap-3 sm:grid-cols-2">
              <label className="text-sm text-slate-300">Role
                <select className="workshop-input" value={form.role} onChange={e => setForm(f => ({ ...f, role: e.target.value }))}>
                  {isLastOwner ? <option value="owner_admin">Owner Admin</option> : ROLES.map(r => <option key={r.key} value={r.key}>{r.label}</option>)}
                </select>
              </label>
              <label className="text-sm text-slate-300">Permission preset
                <select className="workshop-input" value={form.permission_preset} onChange={e => setForm(f => ({ ...f, permission_preset: e.target.value }))}>
                  {Object.entries(PERMISSION_PRESETS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
                </select>
              </label>
            </div>
          ) : <FieldList rows={rows} />}
        </div>
        <div className="panel p-5">
          <h2 className="section-title">Effective Permissions</h2>
          <div className="flex flex-wrap gap-1.5">
            {resolvePermissions(account).map(p => <span key={p} className="rounded-md border border-shire-border bg-shire-raised px-2 py-1 text-xs text-shire-text-secondary">{p}</span>)}
          </div>
        </div>
      </div>

      {projects && (
        <section className="panel mt-6 p-5">
          <h2 className="section-title">Assigned Projects</h2>
          {projects.length === 0 ? <p className="text-sm text-shire-text-muted">No projects assigned.</p> : (
            <div className="grid gap-3 sm:grid-cols-2">
              {projects.map(p => (
                <Link key={p.uuid} to={`/admin/assignments`} className="flex items-center gap-3 rounded-xl border border-shire-border bg-shire-raised px-4 py-3 text-sm hover:border-shire-purple/40">
                  <FolderKanban className="h-5 w-5 text-violet-300" />
                  <div><div className="text-slate-200">{p.project_id}</div><div className="text-xs text-shire-text-muted">{p.status}</div></div>
                </Link>
              ))}
            </div>
          )}
        </section>
      )}
    </>
  );
}