import React, { useState, useEffect, useCallback } from 'react';
import api from '../../services/api';
import { useAuth } from '../../contexts/AuthContext';
import './NomenclatureManager.css';

const EMPTY_FORM = {
  code: '',
  name: '',
  applies_to: 'vehicle',
  kind: 'lookup',
  display_field: 'name',
  sort_order: 0,
  fields: [{ key: 'name', label: 'Name', field_type: 'text', required: true, choices: null }],
};

function NomenclatureManager({ onClose }) {
  const { currentUser } = useAuth();
  const canEdit = !!currentUser?.can_manage_entities;
  const [nomenclatures, setNomenclatures] = useState([]);
  const [selectedId, setSelectedId] = useState(null);
  const [form, setForm] = useState(null); // null = nothing selected
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState('');

  // Load nomenclature list
  const loadNomenclatures = useCallback(async () => {
    setIsLoading(true);
    try {
      const res = await api.get('/api/nomenclatures/');
      const data = res.data.results || res.data;
      setNomenclatures(Array.isArray(data) ? data : []);
    } catch (err) {
      setError('Failed to load nomenclatures');
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadNomenclatures();
  }, [loadNomenclatures]);

  // Select a nomenclature for editing
  const handleSelect = (nom) => {
    setSelectedId(nom.id);
    setError('');
    setForm({
      code: nom.code,
      name: nom.name,
      applies_to: nom.applies_to,
      kind: nom.kind,
      display_field: nom.display_field || 'name',
      sort_order: nom.sort_order || 0,
      fields: (nom.fields || []).map(f => ({
        key: f.key,
        label: f.label || '',
        field_type: f.field_type,
        required: f.required || false,
        choices: f.choices || null,
      })),
    });
  };

  // Start adding new nomenclature
  const handleAdd = () => {
    setSelectedId(null);
    setError('');
    setForm({ ...EMPTY_FORM, fields: [{ ...EMPTY_FORM.fields[0] }] });
  };

  // Cancel editing
  const handleCancel = () => {
    setForm(null);
    setSelectedId(null);
    setError('');
  };

  // Save nomenclature (create or update)
  const handleSave = async () => {
    if (!form) return;
    setIsSaving(true);
    setError('');

    const payload = {
      code: form.code,
      name: form.name,
      applies_to: form.applies_to,
      kind: form.kind,
      display_field: form.display_field,
      sort_order: form.sort_order,
      fields: form.fields.map(f => ({
        key: f.key,
        label: f.label,
        field_type: f.field_type,
        required: f.required,
        choices: f.field_type === 'choice' ? f.choices : null,
      })),
    };

    try {
      if (selectedId) {
        await api.put(`/api/nomenclatures/${selectedId}/`, payload);
      } else {
        const res = await api.post('/api/nomenclatures/', payload);
        setSelectedId(res.data.id);
      }
      await loadNomenclatures();
      setError('');
    } catch (err) {
      const data = err.response?.data;
      if (typeof data === 'string') {
        setError(data);
      } else if (data) {
        const messages = [];
        for (const [key, val] of Object.entries(data)) {
          if (Array.isArray(val)) messages.push(`${key}: ${val.join(', ')}`);
          else if (typeof val === 'string') messages.push(`${key}: ${val}`);
          else messages.push(`${key}: ${JSON.stringify(val)}`);
        }
        setError(messages.join('; ') || 'Failed to save');
      } else {
        setError('Failed to save nomenclature');
      }
    } finally {
      setIsSaving(false);
    }
  };

  // Delete nomenclature
  const handleDelete = async () => {
    if (!selectedId) return;
    if (!window.confirm('Delete this nomenclature and all its entries?')) return;

    try {
      await api.delete(`/api/nomenclatures/${selectedId}/`);
      setForm(null);
      setSelectedId(null);
      await loadNomenclatures();
    } catch {
      setError('Failed to delete nomenclature');
    }
  };

  // --- Field management ---
  const addField = () => {
    setForm(prev => ({
      ...prev,
      fields: [...prev.fields, { key: '', label: '', field_type: 'text', required: false, choices: null }],
    }));
  };

  const updateField = (index, key, value) => {
    setForm(prev => ({
      ...prev,
      fields: prev.fields.map((f, i) => i === index ? { ...f, [key]: value } : f),
    }));
  };

  const removeField = (index) => {
    setForm(prev => ({
      ...prev,
      fields: prev.fields.filter((_, i) => i !== index),
    }));
  };

  const handleOverlayClick = (e) => {
    if (e.target.className === 'nm-overlay') {
      onClose();
    }
  };

  return (
    <div className="nm-overlay" onClick={handleOverlayClick}>
      <div className="nm-content">
        {/* Header */}
        <div className="nm-header">
          <h2>Nomenclatures</h2>
          <button className="nm-close-button" onClick={onClose}>&times;</button>
        </div>

        <div className="nm-body">
          {/* Left panel - List */}
          <div className="nm-list-panel">
            {canEdit && <button className="nm-add-btn" onClick={handleAdd}>+ Add New</button>}

            {isLoading && <div className="nm-loading">Loading...</div>}

            <div className="nm-list">
              {nomenclatures.map(nom => (
                <div
                  key={nom.id}
                  className={`nm-list-item ${selectedId === nom.id ? 'nm-list-item--active' : ''}`}
                  onClick={() => handleSelect(nom)}
                >
                  <div className="nm-list-item-info">
                    <span className="nm-list-item-name">{nom.name}</span>
                    <span className="nm-list-item-meta">
                      {nom.kind === 'lookup' ? 'Lookup' : 'Field'} / {nom.applies_to}
                    </span>
                  </div>
                  {canEdit && (
                    <button
                      className="nm-edit-btn"
                      onClick={(e) => { e.stopPropagation(); handleSelect(nom); }}
                      title="Edit"
                    >
                      &#9998;
                    </button>
                  )}
                </div>
              ))}

              {!isLoading && nomenclatures.length === 0 && (
                <div className="nm-empty">No nomenclatures yet</div>
              )}
            </div>
          </div>

          {/* Right panel - Form */}
          <div className="nm-form-panel">
            {!form ? (
              <div className="nm-placeholder">
                {canEdit ? 'Select a nomenclature to edit or click "+ Add New"' : 'Select a nomenclature to view'}
              </div>
            ) : (
              <div className="nm-form">
                {error && <div className="nm-error">{error}</div>}

                <div className="nm-form-title">
                  {!canEdit ? 'View Nomenclature' : selectedId ? 'Edit Nomenclature' : 'New Nomenclature'}
                </div>

                {/* Basic fields */}
                <div className="nm-form-grid">
                  <div className="nm-form-group">
                    <label>Code</label>
                    <input
                      type="text"
                      value={form.code}
                      onChange={e => setForm(prev => ({ ...prev, code: e.target.value }))}
                      placeholder="e.g. cargo_type"
                      disabled={isSaving || !canEdit}
                    />
                  </div>

                  <div className="nm-form-group">
                    <label>Name</label>
                    <input
                      type="text"
                      value={form.name}
                      onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="e.g. Cargo Type"
                      disabled={isSaving || !canEdit}
                    />
                  </div>

                  <div className="nm-form-group">
                    <label>Applies to</label>
                    <select
                      value={form.applies_to}
                      onChange={e => setForm(prev => ({ ...prev, applies_to: e.target.value }))}
                      disabled={isSaving || !canEdit}
                    >
                      <option value="vehicle">Vehicle</option>
                      <option value="container">Container</option>
                    </select>
                  </div>

                  <div className="nm-form-group">
                    <label>Kind</label>
                    <select
                      value={form.kind}
                      onChange={e => setForm(prev => ({ ...prev, kind: e.target.value }))}
                      disabled={isSaving || !canEdit}
                    >
                      <option value="lookup">Lookup Table</option>
                      <option value="field">Custom Field</option>
                    </select>
                  </div>

                  {form.kind === 'lookup' && (
                    <div className="nm-form-group">
                      <label>Display Field</label>
                      <select
                        value={form.display_field}
                        onChange={e => setForm(prev => ({ ...prev, display_field: e.target.value }))}
                        disabled={isSaving || !canEdit}
                      >
                        {form.fields.filter(f => f.key).map(f => (
                          <option key={f.key} value={f.key}>{f.key}</option>
                        ))}
                      </select>
                    </div>
                  )}
                </div>

                {/* Fields section */}
                <div className="nm-section">
                  <div className="nm-section-header">
                    <h3>Fields</h3>
                    {canEdit && (
                      <button className="nm-section-add" onClick={addField} disabled={isSaving || !canEdit}>
                        + Add Field
                      </button>
                    )}
                  </div>

                  <div className="nm-fields-table">
                    <div className="nm-fields-header">
                      <span>Key</span>
                      <span>Label</span>
                      <span>Type</span>
                      <span>Req</span>
                      <span></span>
                    </div>
                    {form.fields.map((field, idx) => (
                      <div key={idx} className="nm-fields-row">
                        <input
                          type="text"
                          value={field.key}
                          onChange={e => updateField(idx, 'key', e.target.value)}
                          placeholder="key"
                          disabled={isSaving || !canEdit}
                        />
                        <input
                          type="text"
                          value={field.label}
                          onChange={e => updateField(idx, 'label', e.target.value)}
                          placeholder="Label"
                          disabled={isSaving || !canEdit}
                        />
                        <select
                          value={field.field_type}
                          onChange={e => updateField(idx, 'field_type', e.target.value)}
                          disabled={isSaving || !canEdit}
                        >
                          <option value="text">Text</option>
                          <option value="number">Number</option>
                          <option value="bool">Boolean</option>
                          <option value="choice">Choice</option>
                        </select>
                        <input
                          type="checkbox"
                          checked={field.required}
                          onChange={e => updateField(idx, 'required', e.target.checked)}
                          disabled={isSaving || !canEdit}
                        />
                        <button
                          className="nm-remove-btn"
                          onClick={() => removeField(idx)}
                          disabled={isSaving || form.fields.length <= 1}
                          title="Remove field"
                        >
                          &times;
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Actions */}
                <div className="nm-form-actions">
                  {canEdit && selectedId && (
                    <button
                      className="nm-delete-btn"
                      onClick={handleDelete}
                      disabled={isSaving}
                    >
                      Delete
                    </button>
                  )}
                  <div className="nm-form-actions-right">
                    <button
                      className="nm-cancel-btn"
                      onClick={handleCancel}
                      disabled={isSaving}
                    >
                      {canEdit ? 'Cancel' : 'Close'}
                    </button>
                    {canEdit && (
                      <button
                        className="nm-save-btn"
                        onClick={handleSave}
                        disabled={isSaving}
                      >
                        {isSaving ? 'Saving...' : 'Save'}
                      </button>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default NomenclatureManager;
