import { useEffect, useState } from 'react';
import { Plus } from 'lucide-react';
import { dimensionService } from '@/services/dimensionService';
import RecordForm from '@/components/dimensions/RecordForm';
import { ASSEMBLY_FIELDS } from '@/components/dimensions/formConfigs';
export default function AssemblyPositionTab({ component, actor }) {
  const [items, setItems] = useState([]);
  const [adding, setAdding] = useState(false);
  const load = () => dimensionService.componentAssembly(component.uuid).then(setItems);
  useEffect(() => { load(); }, [component.uuid]);
  const save = async (data) => { await dimensionService.saveAssemblyComponent({ ...data, component_uuid: component.uuid, entered_by: actor }, actor); setAdding(false); load(); };
  const cols = ['component_label', 'position_in_assembly', 'orientation', 'installed_visible_length_mm', 'installed_hidden_length_mm', 'max_width_mm', 'max_depth_mm'];
  const labels = ['Label', 'Position', 'Orientation', 'Visible (mm)', 'Hidden (mm)', 'Width (mm)', 'Depth (mm)'];
  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">Assembly positioning. The cover fits around the complete installed assembly, not just one component.</p>
        <button className="btn-primary" onClick={() => setAdding(true)}><Plus/>Add assembly component</button>
      </div>
      {adding && <div className="panel p-6"><RecordForm title="New assembly component" fields={ASSEMBLY_FIELDS} onSave={save} onCancel={() => setAdding(false)} /></div>}
      {items.length === 0 ? (
        <div className="rounded-xl border border-dashed border-white/10 p-8 text-center text-slate-500"><p className="text-sm">No assembly positioning records yet.</p></div>
      ) : (
        <div className="overflow-x-auto"><table className="w-full text-sm"><thead><tr className="text-left text-xs uppercase text-slate-500">{labels.map(l => <th key={l} className="pb-2">{l}</th>)}</tr></thead><tbody>{items.map(i => <tr key={i.uuid} className="border-t border-white/5">{cols.map(c => <td key={c} className="py-2 text-slate-300">{i[c] ?? '—'}</td>)}</tr>)}</tbody></table></div>
      )}
    </div>
  );
}