 @extends('layouts.admin')

@section('heading', $garmentType->name . ($garmentType->name_ta ? ' / ' . $garmentType->name_ta : '') . ' — Measurement Builder')
@section('subheading', 'Add fields, choose input type, and drag to set the order staff will see.')

@section('actions')
  <a href="{{ route('shop.garments.index') }}" class="text-sm" style="color:#6b6470;">← Back to garments</a>
@endsection

@section('content')

<style>
  .field-type-pill {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 5px 12px;
    border-radius: 999px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    border: 1px solid #e6e1d8;
    color: #6b6470;
    background: #fff;
    transition: all 0.15s ease;
    user-select: none;
  }
  .field-type-pill:hover {
    border-color: #C2185B;
    color: #C2185B;
  }
  .field-type-pill[data-checked="true"] {
    background: #5E35B1;
    border-color: #5E35B1;
    color: #fff;
  }
</style>

@if (session('status'))
  <div class="mb-4 text-sm rounded-lg px-4 py-3" style="background:#E1F5EE; color:#0F6E56;">
    {{ session('status') }}
  </div>
@endif

<div class="grid grid-cols-3 gap-6">

  <!-- Configured fields — draggable -->
  <div class="col-span-2 card p-6">
    <p class="text-xs font-medium mb-4" style="color:#1A1625;">Fields on this form <span style="color:#a19a8f;">(drag ⠿ to reorder)</span></p>

    <div id="field-list" class="space-y-3">
      @forelse($configured as $field)
        <div class="px-4 py-3 rounded-lg border" style="border-color:#eee6d8;" data-id="{{ $field->id }}">
          <div class="flex items-start gap-3">
            <span class="cursor-move text-lg pt-1.5" style="color:#a19a8f;">⠿</span>

            <form method="POST" action="{{ route('shop.garments.fields.update', [$garmentType, $field]) }}" class="flex-1 space-y-2">
              @csrf @method('PUT')

              <div class="flex items-center gap-3">
                <input type="text" name="custom_label" value="{{ $field->custom_label }}"
                  placeholder="{{ $field->measurementField->name }}{{ $field->measurementField->name_ta ? ' / ' . $field->measurementField->name_ta : '' }}"
                  class="flex-1 px-3 py-1.5 rounded-lg border text-sm outline-none" style="border-color:#e6e1d8;">
                <span class="text-xs" style="color:#a19a8f;">{{ $field->measurementField->unit }}</span>

                <label class="flex items-center gap-1.5 text-xs whitespace-nowrap" style="color:#6b6470;">
                  <input type="checkbox" name="is_required" value="1" {{ $field->is_required ? 'checked' : '' }} style="accent-color:#C2185B;">
                  Required
                </label>
              </div>

              <div class="flex gap-2 flex-wrap">
                <label class="field-type-pill" data-checked="{{ $field->field_type === 'text' ? 'true' : 'false' }}" title="Free text/number, e.g. chest, length">
                  <input type="radio" name="field_type" value="text" {{ $field->field_type === 'text' ? 'checked' : '' }} class="existing-field-type hidden">
                  📝 Text
                </label>
                <label class="field-type-pill" data-checked="{{ $field->field_type === 'radio' ? 'true' : 'false' }}" title="Radio buttons, pick one, e.g. Fit: Slim / Regular / Loose">
                  <input type="radio" name="field_type" value="radio" {{ $field->field_type === 'radio' ? 'checked' : '' }} class="existing-field-type hidden">
                  🔘 Bullet
                </label>
                <label class="field-type-pill" data-checked="{{ $field->field_type === 'select' ? 'true' : 'false' }}" title="Dropdown, pick one, e.g. Collar: Round / V-neck / Boat">
                  <input type="radio" name="field_type" value="select" {{ $field->field_type === 'select' ? 'checked' : '' }} class="existing-field-type hidden">
                  ▾ Dropdown
                </label>
                <label class="field-type-pill" data-checked="{{ $field->field_type === 'checkbox' ? 'true' : 'false' }}" title="Checkboxes, pick one or more, e.g. Piping, Lining, Pocket">
                  <input type="radio" name="field_type" value="checkbox" {{ $field->field_type === 'checkbox' ? 'checked' : '' }} class="existing-field-type hidden">
                  ☑ Checkbox
                </label>
              </div>

              <div class="options-row" style="{{ in_array($field->field_type, ['radio', 'select', 'checkbox']) ? '' : 'display:none;' }}">
                <input type="text" name="options" value="{{ $field->options }}"
                  placeholder="Comma-separated suggestions e.g. Round neck, V-neck, Boat neck"
                  class="w-full px-3 py-1.5 rounded-lg border text-xs outline-none mt-1" style="border-color:#e6e1d8;">
              </div>

              <div class="flex justify-end">
                <button type="submit" class="text-xs font-medium" style="color:#5E35B1;">Save</button>
              </div>
            </form>

            <form method="POST" action="{{ route('shop.garments.fields.destroy', [$garmentType, $field]) }}" onsubmit="return confirm('Remove this field?');">
              @csrf @method('DELETE')
              <button type="submit" class="text-xs font-medium" style="color:#C2185B;">✕</button>
            </form>
          </div>
        </div>
      @empty
        <p class="text-sm py-6 text-center" style="color:#a19a8f;">No fields added yet — pick from the right to start building the form.</p>
      @endforelse
    </div>
  </div>

  <!-- Available fields to add -->
  <div class="card p-6">
    <p class="text-xs font-medium mb-4" style="color:#1A1625;">Add a field</p>

    @if ($errors->any())
      <div class="mb-3 text-xs rounded-lg px-3 py-2" style="background:#FCEBEB; color:#791F1F;">
        {{ $errors->first() }}
      </div>
    @endif

    <div class="space-y-2 mb-5">
      @forelse($available as $mf)
        <form method="POST" action="{{ route('shop.garments.fields.store', $garmentType) }}" class="flex items-center justify-between px-3 py-2 rounded-lg" style="background:#FFF9F0;">
          @csrf
          <input type="hidden" name="measurement_field_id" value="{{ $mf->id }}">
          <span class="text-sm" style="color:#1A1625;">
            {{ $mf->name }} @if($mf->name_ta) <span style="color:#a19a8f;">/ {{ $mf->name_ta }}</span> @endif
          </span>
          <button type="submit" class="text-xs font-medium" style="color:#C2185B;">+ Add</button>
        </form>
      @empty
        <p class="text-sm" style="color:#a19a8f;">All existing fields have been added.</p>
      @endforelse
    </div>

    <div class="pt-4" style="border-top:1px dashed #e6e1d8;">
      <p class="text-xs font-medium mb-2" style="color:#1A1625;">Can't find it? Create a new field</p>
      <form method="POST" action="{{ route('shop.garments.fields.store', $garmentType) }}" class="space-y-2">
        @csrf
        <input type="text" name="new_field_name" placeholder="Field name (English) e.g. Collar Style" required
          class="w-full px-3 py-2 rounded-lg border text-sm outline-none" style="border-color:#e6e1d8;">
        <input type="text" name="new_field_name_ta" placeholder="தமிழ் பெயர் (optional)"
          class="w-full px-3 py-2 rounded-lg border text-sm outline-none" style="border-color:#e6e1d8;">
        <div class="flex items-center gap-2">
          <select name="new_field_unit" class="flex-1 px-3 py-2 rounded-lg border text-sm outline-none" style="border-color:#e6e1d8;">
            <option value="inch">inch</option>
            <option value="cm">cm</option>
          </select>
        </div>

        <input type="hidden" name="field_type" value="text">

        <button type="submit" class="px-3 py-2 rounded-lg text-xs font-medium text-white" style="background:#5E35B1;">+ Create & add</button>
      </form>
    </div>
  </div>

</div>

@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
  const list = document.getElementById('field-list');
  if (list) {
    new Sortable(list, {
      handle: '.cursor-move',
      animation: 150,
      onEnd: function () {
        const order = Array.from(list.children).map(el => el.dataset.id);
        fetch("{{ route('shop.garments.fields.reorder', $garmentType) }}", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}',
          },
          body: JSON.stringify({ order }),
        });
      },
    });
  }

  // Toggle pill highlight + options input for EXISTING configured fields
  document.querySelectorAll('.existing-field-type').forEach(radio => {
    radio.addEventListener('change', function () {
      // reset all pills in this form, then highlight the selected one
      this.closest('form').querySelectorAll('.field-type-pill').forEach(pill => {
        pill.dataset.checked = 'false';
      });
      this.closest('.field-type-pill').dataset.checked = 'true';

      // show/hide the options input
      const optionsRow = this.closest('form').querySelector('.options-row');
      if (['radio', 'select', 'checkbox'].includes(this.value)) {
        optionsRow.style.display = '';
      } else {
        optionsRow.style.display = 'none';
      }
    });
  });
</script>
@endpush
