import { useEffect, useState } from 'react';
import { UserPlus, FolderKanban } 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 { adapters, newUuid, migrationFields } from '@/services/serviceConfig';
import { useAccount } from '@/lib/AccountContext';

const TYPES = ['primary_builder', 'supporting_builder', 'measurement', 'design', 'ossiguard', 'manufacturing', 'inspection'];
const STATUSES = ['Assigned', 'Accepted', 'In Progress', 'Blocked', 'Review Required', 'Complete', 'Reassigned'];

export default function Assignments() {
  const { account: me } = useAccount();
  const [projects, setProjects] = useState(null);
  const [builders, setBuilders] = useState(null);
  const [assignments, setAssignments] = useState(null);
  const [form, setForm] = useState(null);
  const [toast, setToast] = useState('');

  const load = () => {
    adapters.database.list('CoverProject').then(setProjects);
    accountService.listByRole('builder').then(setBuilders);
    adapters.database.list('ProjectAssignment').then(setAssignments);
  };
  useEffect(() => { load(); }, []);

  const assign = async (e) => {
    e.preventDefault();
    const f = new FormData(e.target);
    const projectUuid = f.get('project_uuid');
    const userId = f.get('user_id');
    const assignmentType = f.get('assignment_type');
    const project = projects.find(p => p.uuid === projectUuid);
    const builder = builders.find(b => b.user_id === userId);
    const actor = me?.display_name || 'Admin';
    await adapters.database.create('ProjectAssignment', {
      uuid: newUuid('assign'), project_uuid: projectUuid, project_id: project?.project_id,
      user_id: userId, user_name: builder?.display_name, account_uuid: builder?.uuid,
      assignment_type: assignmentType, assigned_by_name: actor, assigned_date: new Date().toISOString(),
      status: 'Assigned', notes: f.get('notes'), due_date: f.get('due_date'),
      ...migrationFields(actor),
    });
    await accountService.assignProject(builder, projectUuid, actor);
    setToast('Project assigned and builder notified (in-app).');
    setForm(null); load(); setTimeout(() => setToast(''), 3000);
  };

  const setAssignStatus = async (a, status) => {
    await adapters.database.update('ProjectAssignment', a.id, { status, updated_by_name: me?.display_name });
    load();
  };

  if (!projects || !builders || !assignments) return <LoadingPanel label="Loading assignments" />;

  return (
    <>
      <PageHeader eyebrow="Project Assignments" title="Builder Workload & Assignments"
        description="Assign Builders to projects by task type. Builders only see projects assigned to them."
        action={<button className="btn-primary" onClick={() => setForm({})}><UserPlus />New Assignment</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={assign} className="panel mb-6 p-6">
          <h2 className="section-title">New Assignment</h2>
          <div className="grid gap-4 sm:grid-cols-2">
            <label className="text-sm text-slate-300">Project
              <select name="project_uuid" required className="workshop-input">
                {projects.map(p => <option key={p.uuid} value={p.uuid}>{p.project_id} — {p.status}</option>)}
              </select>
            </label>
            <label className="text-sm text-slate-300">Builder
              <select name="user_id" required className="workshop-input">
                {builders.map(b => <option key={b.user_id} value={b.user_id}>{b.display_name} ({b.builder_title || 'Builder'})</option>)}
              </select>
            </label>
            <label className="text-sm text-slate-300">Assignment type
              <select name="assignment_type" className="workshop-input">{TYPES.map(t => <option key={t} value={t}>{t.replace('_', ' ')}</option>)}</select>
            </label>
            <label className="text-sm text-slate-300">Due date (optional)<input name="due_date" type="date" className="workshop-input" /></label>
            <label className="text-sm text-slate-300 sm:col-span-2">Notes<input name="notes" className="workshop-input" /></label>
          </div>
          <div className="mt-4 flex gap-2"><button className="btn-primary" type="submit">Assign</button><button type="button" className="btn-secondary" onClick={() => setForm(null)}>Cancel</button></div>
        </form>
      )}

      {assignments.length === 0 ? <p className="text-sm text-shire-text-muted">No assignments yet.</p> : (
        <div className="grid gap-3">
          {assignments.map(a => (
            <div key={a.uuid} className="panel flex flex-wrap items-center justify-between gap-3 p-4">
              <div className="flex items-center gap-3"><FolderKanban className="h-5 w-5 text-violet-300" />
                <div><div className="text-sm font-medium text-slate-200">{a.project_id}</div>
                  <div className="text-xs text-shire-text-muted">{a.user_name} · {a.assignment_type.replace('_', ' ')} · {a.assigned_by_name}</div></div>
              </div>
              <select className="workshop-input mt-0 w-auto" value={a.status} onChange={e => setAssignStatus(a, e.target.value)}>
                {STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </div>
          ))}
        </div>
      )}
    </>
  );
}