import { useEffect, useState } from 'react';
import { Plus, FileCheck } from 'lucide-react';
import { dimensionService } from '@/services/dimensionService';
import { MANUFACTURER_SPEC_FIELDS } from '@/services/dimensionDefinitions';
import SpecImportForm from '@/components/dimensions/SpecImportForm';
import StatusPill from '@/components/workshop/StatusPill';
export default function ManufacturerSpecsTab({ component, actor }) {
  const [specs, setSpecs] = useState([]);
  const [adding, setAdding] = useState(false);
  const load = () => dimensionService.specs(component.uuid).then(setSpecs);
  useEffect(() => { load(); }, [component.uuid]);
  const save = async (data) => { await dimensionService.importSpec(component, data, actor); setAdding(false); load(); };
  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <p className="text-sm text-slate-400">Verified manufacturer specifications from official sources only.</p>
        <button className="btn-primary" onClick={() => setAdding(true)}><Plus/>Import manufacturer specs</button>
      </div>
      {adding && <div className="panel p-6"><SpecImportForm component={component} onSave={save} onCancel={() => setAdding(false)} /></div>}
      {specs.length === 0 ? (
        <div className="rounded-xl border border-dashed border-white/10 p-8 text-center text-slate-500">
          <FileCheck className="mx-auto mb-2 h-8 w-8"/><p className="text-sm">No manufacturer specifications imported yet. External width, depth and real envelope dimensions remain missing.</p>
        </div>
      ) : specs.map(s => (
        <div key={s.uuid} className="panel p-5">
          <div className="flex items-start justify-between">
            <div><h3 className="text-lg font-semibold text-white">{s.document_title || 'Untitled document'}</h3><p className="text-xs text-slate-500">{s.document_identifier} · v{s.document_version} · {s.publication_date}</p></div>
            <StatusPill tone={s.is_official_source ? 'green' : 'amber'}>{s.is_official_source ? 'Official source' : 'Unofficial'}</StatusPill>
          </div>
          <div className="mt-4 grid gap-2 sm:grid-cols-3">
            {MANUFACTURER_SPEC_FIELDS.filter(([k]) => s[k] != null && s[k] !== '').map(([k, label]) => (
              <div key={k} className="rounded-lg bg-white/5 px-3 py-2"><p className="text-xs text-slate-500">{label}</p><p className="text-sm text-slate-200">{s[k]}</p></div>
            ))}
          </div>
          <p className="mt-3 text-xs text-slate-500">Imported {s.date_imported} by {s.imported_by}{s.verified_by ? ` · Verified by ${s.verified_by}` : ' · Not manually verified'}</p>
        </div>
      ))}
    </div>
  );
}