import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { UserPlus, Search, Send, Copy, Ban, RotateCcw, KeyRound, Archive } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { accountService } from '@/services/accountService';
import { invitationService } from '@/services/invitationService';
import { useAccount } from '@/lib/AccountContext';
import { ROLES } from '@/config/permissions';

export default function AdminUsers() {
  const { account: me } = useAccount();
  const [accounts, setAccounts] = useState(null);
  const [invites, setInvites] = useState(null);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [inviteForm, setInviteForm] = useState(null);
  const [copied, setCopied] = useState('');
  const [toast, setToast] = useState('');

  const load = () => {
    accountService.list().then(setAccounts);
    invitationService.list().then(setInvites);
  };
  useEffect(() => { load(); }, []);

  const filtered = (accounts || []).filter(a => {
    if (roleFilter && a.role !== roleFilter) return false;
    if (statusFilter && a.account_status !== statusFilter) return false;
    if (search && !`${a.display_name} ${a.email}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const isLastOwner = (a) => a.role === 'owner_admin' && a.account_status === 'Active' &&
    accounts.filter(x => x.role === 'owner_admin' && x.account_status === 'Active').length <= 1;

  const act = async (fn, msg) => { await fn(); load(); if (msg) setToast(msg); setTimeout(() => setToast(''), 3000); };

  const sendInvite = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    const data = Object.fromEntries(f);
    const actor = me?.display_name || 'Admin';
    const existing = await accountService.getByEmail(data.email);
    if (existing) { setToast('An account already exists for that email.'); setInviteForm(null); return; }
    await invitationService.create({
      email: data.email, intended_role: data.intended_role,
      permission_preset: data.permission_preset || data.intended_role,
      notes: data.notes,
    }, actor);
    setToast('Invitation created. Email delivery is not configured — copy and provide the secure invitation link manually.');
    setInviteForm(null);
    load();
    setTimeout(() => setToast(''), 5000);
  };

  const copyLink = (inv) => { navigator.clipboard.writeText(invitationService.linkForCopy(inv)); setCopied(inv.uuid); setTimeout(() => setCopied(''), 2000); };

  const pendingInvites = (invites || []).filter(i => i.status === 'pending');

  return (
    <>
      <PageHeader eyebrow="User Management" title="Users & Invitations"
        description="Owner/Admin only. Invite Builders, Customers and Admins. The last Owner Admin cannot be removed."
        action={<button className="btn-primary" onClick={() => setInviteForm({})}><UserPlus />Invite User</button>} />

      {toast && <div className="mb-4 rounded-lg border border-shire-purple/40 bg-shire-purple/10 p-3 text-sm text-violet-200">{toast}</div>}

      {inviteForm && (
        <form onSubmit={sendInvite} className="panel mb-6 p-6">
          <h2 className="section-title">New Invitation</h2>
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="text-sm text-slate-300">Email<input name="email" type="email" required className="workshop-input" /></label>
            <label className="text-sm text-slate-300">Role
              <select name="intended_role" className="workshop-input" defaultValue="builder">
                {me?.role === 'owner_admin' && <option value="admin">Admin</option>}
                <option value="builder">Builder / Designer</option>
                <option value="customer">Customer</option>
              </select>
            </label>
            <label className="text-sm text-slate-300">Permission preset
              <select name="permission_preset" className="workshop-input">
                <option value="builder">Builder</option>
                <option value="senior_builder">Senior Builder</option>
                <option value="design_only">Design Only</option>
                <option value="measurement_only">Measurement Only</option>
                <option value="manufacturing_only">Manufacturing Only</option>
                <option value="customer">Customer</option>
              </select>
            </label>
            <label className="text-sm text-slate-300">Notes (optional)<input name="notes" className="workshop-input" /></label>
          </div>
          <p className="mt-3 text-xs text-amber-300">Public users cannot choose Builder or Admin. Email delivery is not configured — you must copy the invitation link manually after creation.</p>
          <div className="mt-4 flex gap-2">
            <button className="btn-primary" type="submit"><Send />Create Invitation</button>
            <button type="button" className="btn-secondary" onClick={() => setInviteForm(null)}>Cancel</button>
          </div>
        </form>
      )}

      {pendingInvites.length > 0 && (
        <section className="panel mb-6 p-5">
          <h2 className="section-title">Pending Invitations ({pendingInvites.length})</h2>
          <div className="space-y-2">
            {pendingInvites.map(i => (
              <div key={i.uuid} className="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-shire-border bg-shire-raised px-4 py-3 text-sm">
                <div><span className="text-slate-200">{i.email}</span> <StatusPill tone="amber">{i.intended_role}</StatusPill></div>
                <div className="flex gap-2">
                  <button className="icon-btn" title="Copy invitation link" onClick={() => copyLink(i)}><Copy />{copied === i.uuid && <span className="ml-1 text-xs text-emerald-300">copied</span>}</button>
                  <button className="icon-btn" title="Resend" onClick={() => act(() => invitationService.resend(i, me?.display_name), 'Invitation resent — copy the new link manually.')}><Send /></button>
                  <button className="icon-btn" title="Revoke" onClick={() => act(() => invitationService.revoke(i, me?.display_name), 'Invitation revoked.')}><Ban /></button>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      <div className="mb-4 flex flex-wrap gap-3">
        <label className="relative flex-1 min-w-48">
          <Search className="absolute left-4 top-3.5 h-5 w-5 text-slate-500" />
          <input className="workshop-input mt-0 pl-12" placeholder="Search name or email" value={search} onChange={e => setSearch(e.target.value)} />
        </label>
        <select className="workshop-input mt-0 w-auto" value={roleFilter} onChange={e => setRoleFilter(e.target.value)}>
          <option value="">All roles</option>
          {ROLES.map(r => <option key={r.key} value={r.key}>{r.label}</option>)}
        </select>
        <select className="workshop-input mt-0 w-auto" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
          <option value="">All statuses</option>
          <option>Active</option><option>Invited</option><option>Suspended</option><option>Archived</option>
        </select>
      </div>

      {!accounts ? <LoadingPanel label="Loading users" /> : (
        <div className="panel overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-shire-raised text-left text-xs uppercase tracking-wider text-shire-text-muted">
              <tr><th className="p-3">Name</th><th className="p-3">Role</th><th className="p-3">Status</th><th className="p-3">Linked</th><th className="p-3">Last login</th><th className="p-3">Actions</th></tr>
            </thead>
            <tbody className="divide-y divide-shire-border">
              {filtered.map(a => (
                <tr key={a.uuid} className="hover:bg-shire-purple/5">
                  <td className="p-3"><Link to={`/admin/users/${a.uuid}`} className="font-medium text-violet-300 hover:underline">{a.display_name || a.email}</Link><div className="text-xs text-shire-text-muted">{a.email}</div></td>
                  <td className="p-3">{ROLES.find(r => r.key === a.role)?.label || a.role}</td>
                  <td className="p-3"><StatusPill tone={a.account_status === 'Active' ? 'green' : a.account_status === 'Suspended' ? 'red' : 'amber'}>{a.account_status}</StatusPill></td>
                  <td className="p-3 text-xs text-shire-text-secondary">{a.customer_number || (a.builder_title ? `Builder: ${a.builder_title}` : '—')}</td>
                  <td className="p-3 text-xs text-shire-text-muted">{a.last_login ? new Date(a.last_login).toLocaleDateString() : '—'}</td>
                  <td className="p-3">
                    <div className="flex gap-1">
                      {a.account_status === 'Active' && !isLastOwner(a) && <button className="icon-btn" title="Suspend" onClick={() => act(() => accountService.suspend(a, 'Suspended by admin', me?.display_name), 'Account suspended.')}><Ban /></button>}
                      {a.account_status === 'Suspended' && <button className="icon-btn" title="Reactivate" onClick={() => act(() => accountService.reactivate(a, me?.display_name), 'Account reactivated.')}><RotateCcw /></button>}
                      <button className="icon-btn" title="Revoke sessions" onClick={() => act(() => accountService.revokeSessions(a, me?.display_name), 'Sessions revoked.')}><KeyRound /></button>
                      {!isLastOwner(a) && a.account_status !== 'Archived' && <button className="icon-btn" title="Archive" onClick={() => act(() => accountService.archive(a, me?.display_name), 'Account archived.')}><Archive /></button>}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  );
}