import { useEffect, useState } from 'react';
import { dimensionService } from '@/services/dimensionService';
import { ENVELOPE_DIMENSIONS } from '@/services/dimensionDefinitions';
import ComponentDiagrams from '@/components/dimensions/ComponentDiagrams';
import DimensionEntryForm from '@/components/dimensions/DimensionEntryForm';
import StatusPill from '@/components/workshop/StatusPill';
export default function ExternalEnvelopeTab({ component, actor }) {
  const [dims, setDims] = useState([]);
  const load = () => dimensionService.dimensions(component.uuid).then(setDims);
  useEffect(() => { load(); }, [component.uuid]);
  const onSave = async (data) => { const dim = ENVELOPE_DIMENSIONS.find(d => d[0] === data.dimension_key); await dimensionService.saveDimension({ component_uuid: component.uuid, dimension_key: data.dimension_key, dimension_name: dim[1], category: 'External envelope', source: data.source, value_mm: data.value_mm, original_value: data.original_value, original_unit: data.entered_unit, entered_unit: data.entered_unit, confidence: data.confidence, verification_status: 'Entered', entered_by: actor, notes: data.notes }, actor); load(); };
  const dimsMap = Object.fromEntries(dims.map(d => [d.dimension_key, d]));
  return (
    <div className="space-y-5">
      <ComponentDiagrams dims={dimsMap} />
      <div>
        <h3 className="section-title">Envelope dimensions</h3>
        <div className="overflow-x-auto"><table className="w-full text-sm">
          <thead><tr className="text-left text-xs uppercase text-slate-500"><th className="pb-2">Dimension</th><th className="pb-2">Value</th><th className="pb-2">Source</th><th className="pb-2">Status</th></tr></thead>
          <tbody>
            {ENVELOPE_DIMENSIONS.map(([key, label, unit]) => {
              const d = dimsMap[key];
              return <tr key={key} className="border-t border-white/5"><td className="py-2 text-slate-300">{label}</td><td className="py-2 text-slate-200">{d?.value_mm != null ? `${d.value_mm} ${unit === 'mm' ? 'mm' : ''}` : d?.text_value || '—'}</td><td className="py-2 text-slate-400">{d?.source || 'Not entered'}</td><td className="py-2"><StatusPill tone={d?.verification_status === 'Verified manufacturer value' ? 'green' : d ? 'amber' : 'slate'}>{d?.verification_status || 'Unknown'}</StatusPill></td></tr>;
            })}
          </tbody>
        </table></div>
      </div>
      <DimensionEntryForm dimensions={ENVELOPE_DIMENSIONS} onSave={onSave} />
    </div>
  );
}