import { useEffect, useState } from 'react';
import { Mail, Copy, Send, Ban, RotateCcw } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import LoadingPanel from '@/components/workshop/LoadingPanel';
import StatusPill from '@/components/workshop/StatusPill';
import { invitationService } from '@/services/invitationService';
import { useAccount } from '@/lib/AccountContext';

export default function Invitations() {
  const { account: me } = useAccount();
  const [invites, setInvites] = useState(null);
  const [copied, setCopied] = useState('');
  const [toast, setToast] = useState('');
  const [form, setForm] = useState(null);

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

  const act = async (fn, msg) => { await fn(); load(); if (msg) { setToast(msg); setTimeout(() => setToast(''), 4000); } };
  const copyLink = (inv) => { navigator.clipboard.writeText(invitationService.linkForCopy(inv)); setCopied(inv.uuid); setTimeout(() => setCopied(''), 2000); };

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

  // inline to avoid importing accountService just for this check
  const accountService_getByEmail = async (email) => {
    const { adapters } = await import('@/services/serviceConfig');
    const r = await adapters.database.filter('WorkshopAccount', { email });
    return r[0];
  };

  if (!invites) return <LoadingPanel label="Loading invitations" />;
  const pending = invites.filter(i => i.status === 'pending');

  return (
    <>
      <PageHeader eyebrow="Administration" title="Invitations"
        description="Create, copy, resend and revoke invitations. Email delivery is not configured — links must be provided manually."
        action={<button className="btn-primary" onClick={() => setForm({})}><Mail />New Invitation</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>}

      {form && (
        <form onSubmit={create} 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<input name="notes" className="workshop-input" /></label>
          </div>
          <div className="mt-4 flex gap-2"><button className="btn-primary" type="submit">Create</button><button type="button" className="btn-secondary" onClick={() => setForm(null)}>Cancel</button></div>
        </form>
      )}

      {invites.length === 0 ? <p className="text-sm text-shire-text-muted">No invitations yet.</p> : (
        <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">Email</th><th className="p-3">Role</th><th className="p-3">Status</th><th className="p-3">Expiry</th><th className="p-3">Actions</th></tr>
            </thead>
            <tbody className="divide-y divide-shire-border">
              {invites.map(i => (
                <tr key={i.uuid} className="hover:bg-shire-purple/5">
                  <td className="p-3 text-slate-200">{i.email}</td>
                  <td className="p-3">{i.intended_role}</td>
                  <td className="p-3"><StatusPill tone={i.status === 'pending' ? 'amber' : i.status === 'accepted' ? 'green' : 'slate'}>{i.status}</StatusPill></td>
                  <td className="p-3 text-xs text-shire-text-muted">{i.expiry_date ? new Date(i.expiry_date).toLocaleString() : '—'}</td>
                  <td className="p-3">
                    {i.status === 'pending' && (
                      <div className="flex gap-1">
                        <button className="icon-btn" title="Copy 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), 'Resent — copy the new link.')}><Send /></button>
                        <button className="icon-btn" title="Revoke" onClick={() => act(() => invitationService.revoke(i, me?.display_name), 'Revoked.')}><Ban /></button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </>
  );
}