// ProjectDataPicker — Single Source of Truth picker
// Used in BOQ, Contract, PR/PO, Billing, Drawings forms
// 1. Forces user to select a project (from ProjectManager)
// 2. Validates required project fields exist; if missing, prompts to fill
// 3. After fill, saves back to ProjectManager so next time it auto-fills
// 4. Calls onProjectData(project) when project is selected AND complete

const FIELD_DEFS = {
  name:            { th: 'ชื่อโครงการ',         en: 'Project Name',     type: 'text',   required: true  },
  client:          { th: 'ชื่อลูกค้า',           en: 'Client',           type: 'text',   required: true  },
  site:            { th: 'ที่ตั้งโครงการ',       en: 'Site',             type: 'text',   required: false },
  value:           { th: 'มูลค่าโครงการ',        en: 'Value (THB)',      type: 'number', required: false },
  project_type:    { th: 'ประเภทงาน',            en: 'Project Type',     type: 'select', required: true  },
  floor_area:      { th: 'พื้นที่ใช้สอย (ตร.ม.)', en: 'Floor area',      type: 'number', required: false },
  contract_signed: { th: 'วันเริ่มสัญญา',         en: 'Contract start',   type: 'date',   required: false },
  handover_date:   { th: 'วันสิ้นสุดสัญญา',       en: 'Contract end',     type: 'date',   required: false },
};

window.ProjectDataPicker = function ProjectDataPicker({
  lang = 'th',
  value,
  onChange,
  required = ['name', 'client', 'project_type'],
  onProjectData,
  compact = false,
}) {
  const [projects, setProjects] = React.useState(() => window.ProjectManager?.list() || []);
  const [showFill, setShowFill] = React.useState(false);

  React.useEffect(() => {
    if (!window.ProjectManager) return;
    return window.ProjectManager.subscribe(setProjects);
  }, []);

  const project = value ? projects.find(p => p.code === value) : null;
  const missing = project
    ? required.filter(f => !project[f] || (typeof project[f] === 'string' && !project[f].trim()))
    : [];

  // Notify parent when project is selected AND complete
  React.useEffect(() => {
    if (project && missing.length === 0 && onProjectData) onProjectData(project);
  }, [project?.code, missing.length]);

  const T = (en, th) => lang === 'th' ? th : en;

  if (projects.length === 0) {
    return (
      <div style={{ padding: 14, background: 'rgba(155,44,44,0.08)', border: '1px solid rgba(155,44,44,0.25)', borderRadius: 8, fontSize: 12.5 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <div>
            <strong style={{ color: 'var(--rose)', fontSize: 13 }}>🚫 {T('No projects exist', 'ยังไม่มีโครงการในระบบ')}</strong>
            <div style={{ color: 'var(--ink-soft)', marginTop: 4, fontSize: 11.5 }}>
              {T('You must create a project in "Project Overview" first.', 'ต้องสร้างโครงการที่หน้า "ภาพรวมโครงการ" ก่อน')}
            </div>
          </div>
          <button className="btn btn-sm btn-primary" onClick={() => window.__appNav?.('overview')}>
            → {T('Go to Project Overview', 'ไปที่ภาพรวมโครงการ')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      {!compact && (
        <div className="micro" style={{ marginBottom: 6 }}>
          📁 {T('Reference project (from Project Overview) *', 'โครงการอ้างอิง (จากภาพรวมโครงการ) *')}
        </div>
      )}

      <select value={value || ''} onChange={(e) => onChange(e.target.value)}
        style={{
          width: '100%', padding: '9px 12px',
          background: 'var(--glass-2)', border: '1px solid ' + (project ? 'var(--line)' : 'var(--syk-blue)'),
          borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit',
        }}>
        <option value="">— {T('Select a project', 'เลือกโครงการ')} —</option>
        {projects.map(p => {
          const labelType = p.project_type && p.project_type !== 'OTH' ? `[${p.project_type}] ` : '';
          return (
            <option key={p.code} value={p.code}>{labelType}{p.code} — {p.name || T('(no name)', '(ไม่มีชื่อ)')}</option>
          );
        })}
      </select>

      {/* Missing required fields warning */}
      {project && missing.length > 0 && (
        <div style={{
          marginTop: 8, padding: 12,
          background: 'rgba(181,99,0,0.08)',
          border: '1px solid rgba(181,99,0,0.25)',
          borderRadius: 6,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap',
        }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ color: 'var(--amber)', fontWeight: 600, fontSize: 12.5 }}>
              ⚠ {T('Project missing required fields', 'โครงการนี้ขาดข้อมูลที่จำเป็น')}
            </div>
            <div style={{ color: 'var(--ink-soft)', fontSize: 11, marginTop: 4 }}>
              {T('Missing:', 'ขาด:')} {missing.map(f => (FIELD_DEFS[f]?.[lang] || f)).join(', ')}
            </div>
          </div>
          <button onClick={() => setShowFill(true)} className="btn btn-sm"
            style={{ background: 'var(--amber)', color: '#fff', borderColor: 'var(--amber)' }}>
            + {T('Fill missing', 'เติมข้อมูล')}
          </button>
        </div>
      )}

      {/* Project ready preview */}
      {project && missing.length === 0 && !compact && (
        <div style={{
          marginTop: 8, padding: '8px 12px',
          background: 'var(--syk-blue-tint)',
          border: '1px solid rgba(30,58,95,0.2)',
          borderRadius: 6,
          fontSize: 11.5,
          display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center',
        }}>
          <span style={{ color: 'var(--syk-blue)' }}>✓ {T('Auto-filled from project', 'ดึงข้อมูลจากโครงการแล้ว')}</span>
          {project.project_type && project.project_type !== 'OTH' && (
            <span style={{ padding: '1px 6px', background: 'var(--bg-1)', border: '1px solid var(--line)', borderRadius: 3, fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 10 }}>
              {project.project_type}
            </span>
          )}
          <span style={{ color: 'var(--ink-soft)' }}>· <strong>{project.name}</strong></span>
          {project.client && <span style={{ color: 'var(--ink-mute)' }}>· {project.client}</span>}
          {project.site && <span style={{ color: 'var(--ink-mute)' }}>· 📍 {project.site}</span>}
        </div>
      )}

      {showFill && project && (
        <MissingFieldsModal lang={lang} project={project} fields={missing}
          onClose={() => setShowFill(false)}
          onSave={(updates) => {
            window.ProjectManager.update(project.code, updates);
            setShowFill(false);
          }} />
      )}
    </div>
  );
};

function MissingFieldsModal({ lang, project, fields, onClose, onSave }) {
  const [form, setForm] = React.useState(() =>
    Object.fromEntries(fields.map(f => [f, project[f] || (FIELD_DEFS[f]?.type === 'number' ? 0 : '')]))
  );
  const T = (en, th) => lang === 'th' ? th : en;

  const inpStyle = {
    width: '100%', padding: '9px 12px',
    background: 'var(--glass-2)', border: '1px solid var(--line)',
    borderRadius: 8, color: 'var(--ink)', fontSize: 13, fontFamily: 'inherit',
  };

  const submit = () => {
    // Validate all fields filled
    for (const f of fields) {
      const v = form[f];
      if (v === '' || v == null) {
        alert(T('Please fill: ', 'กรุณากรอก: ') + (FIELD_DEFS[f]?.[lang] || f));
        return;
      }
    }
    onSave(form);
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)',
      backdropFilter: 'blur(6px)', zIndex: 1100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div className="card anim-fadein" onClick={(e) => e.stopPropagation()}
        style={{ width: 'min(540px, 100%)', padding: 24, maxHeight: '90vh', overflowY: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
          <div>
            <div className="micro">{T('Fill project info', 'เติมข้อมูลโครงการ')}</div>
            <div style={{ fontSize: 16, fontWeight: 700, marginTop: 4 }}>
              {project.code} — {project.name || T('(no name)', '(ไม่มีชื่อ)')}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 0, color: 'var(--ink-mute)', cursor: 'pointer', fontSize: 18 }}>×</button>
        </div>

        <div style={{ padding: 10, background: 'rgba(30,58,95,0.06)', borderRadius: 6, fontSize: 11.5, color: 'var(--ink-soft)', marginBottom: 14, lineHeight: 1.6 }}>
          💡 {T('Filling these fields will update the project. All future forms referencing this project will use the updated data.',
                 'กรอกแล้วจะอัปเดตข้อมูลโครงการ ฟอร์มอื่นทุกฟอร์มที่อ้างอิงโครงการนี้จะใช้ข้อมูลที่อัปเดตด้วย')}
        </div>

        {fields.map(f => {
          const def = FIELD_DEFS[f] || { th: f, en: f, type: 'text' };
          return (
            <div key={f} style={{ marginBottom: 12 }}>
              <div className="micro" style={{ marginBottom: 6 }}>{def[lang] || f} *</div>
              {def.type === 'select' && f === 'project_type' && window.PROJECT_TYPES ? (
                <select value={form[f] || ''} onChange={(e) => setForm({ ...form, [f]: e.target.value })} style={inpStyle}>
                  <option value="">— {T('Select', 'เลือก')} —</option>
                  {window.PROJECT_TYPES.map(t => (
                    <option key={t.code} value={t.code}>{t.code} — {lang === 'th' ? t.th : t.en}</option>
                  ))}
                </select>
              ) : def.type === 'number' ? (
                <input type="number" value={form[f] || ''} onChange={(e) => setForm({ ...form, [f]: Number(e.target.value) || 0 })} style={inpStyle} />
              ) : def.type === 'date' ? (
                <input type="date" value={form[f] || ''} onChange={(e) => setForm({ ...form, [f]: e.target.value })} style={inpStyle} />
              ) : (
                <input type="text" value={form[f] || ''} onChange={(e) => setForm({ ...form, [f]: e.target.value })} style={inpStyle} />
              )}
            </div>
          );
        })}

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <button className="btn" style={{ flex: 1, justifyContent: 'center' }} onClick={onClose}>{T('Cancel', 'ยกเลิก')}</button>
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center' }} onClick={submit}>
            ✓ {T('Save & continue', 'บันทึก & ใช้ต่อ')}
          </button>
        </div>
      </div>
    </div>
  );
}
