import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { HardHat, Save } from 'lucide-react';
import PageHeader from '@/components/workshop/PageHeader';
import { invitationService } from '@/services/invitationService';
import { useAccount } from '@/lib/AccountContext';
import { BUILDER_SKILLS, PERMISSION_PRESETS } from '@/config/permissions';

export default function NewBuilder() {
  const { account: me } = useAccount();
  const nav = useNavigate();
  const [skills, setSkills] = useState([]);
  const [toast, setToast] = useState('');

  const toggleSkill = (s) => setSkills(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]);

  const submit = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    const actor = me?.display_name || 'Admin';
    const existing = await import('@/services/serviceConfig').then(({ adapters }) => adapters.database.filter('WorkshopAccount', { email: f.get('email') })).then(r => r[0]);
    if (existing) { setToast('An account already exists for that email.'); return; }
    const inv = await invitationService.create({
      email: f.get('email'), intended_role: 'builder',
      permission_preset: f.get('permission_preset') || 'builder',
      linked_builder_profile_uuid: f.get('builder_profile_uuid') || null,
      notes: `Builder title: ${f.get('builder_title')}. Skills: ${skills.join(', ')}. Phone: ${f.get('phone')}. Notes: ${f.get('internal_notes')}`,
    }, actor);
    setToast('Builder invitation created. Email delivery is not configured — copy and provide the secure invitation link manually.');
    setTimeout(() => nav('/admin/invitations'), 4000);
  };

  return (
    <>
      <PageHeader eyebrow="Administration" title="Invite Builder / Designer"
        description="Builder accounts are only created through authorised invitation. Public self-registration is not available." />
      {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 onSubmit={submit} className="panel max-w-2xl p-6">
        <h2 className="section-title"><HardHat className="mr-1 inline h-5 w-5" />Builder Details</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <label className="text-sm text-slate-300">Full name<input name="full_name" required className="workshop-input" /></label>
          <label className="text-sm text-slate-300">Preferred name<input name="preferred_name" className="workshop-input" /></label>
          <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">Phone (optional)<input name="phone" className="workshop-input" /></label>
          <label className="text-sm text-slate-300">Builder title<input name="builder_title" placeholder="e.g. Senior Prosthetic Designer" className="workshop-input" /></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>
            </select>
          </label>
          <label className="text-sm text-slate-300">Account expiry (optional)<input name="account_expiry" type="date" className="workshop-input" /></label>
          <label className="text-sm text-slate-300">Builder profile UUID (optional)<input name="builder_profile_uuid" className="workshop-input" /></label>
        </div>
        <div className="mt-4">
          <p className="text-sm text-slate-300">Skill tags (organisational only — not professional certification)</p>
          <div className="mt-2 flex flex-wrap gap-2">
            {BUILDER_SKILLS.map(s => (
              <button key={s} type="button" onClick={() => toggleSkill(s)} className={`rounded-full border px-3 py-1 text-xs transition ${skills.includes(s) ? 'border-shire-purple bg-shire-purple/15 text-violet-200' : 'border-shire-border bg-shire-raised text-slate-400 hover:border-shire-purple/40'}`}>{s}</button>
            ))}
          </div>
        </div>
        <label className="mt-4 block text-sm text-slate-300">Internal notes<textarea name="internal_notes" rows={3} className="workshop-input" /></label>
        <div className="mt-5 flex gap-2"><button className="btn-primary" type="submit"><Save />Create Builder Invitation</button></div>
      </form>
    </>
  );
}