import { useNavigate } from '@solidjs/router';
import { createMemo, createSignal, For, Show } from 'solid-js';
import AdminShell from '~/components/AdminShell';

const API = '/api/gateway';

const EXTERNAL_ROLES = ['company', 'job_seeker', 'customer', 'photographer', 'video_editor', 'graphic_designer', 'social_media_manager', 'fitness_trainer', 'catering_services', 'makeup_artist', 'tutor', 'developer'];

const FIELD_TYPES = ['text', 'textarea', 'number', 'email', 'tel', 'date', 'select', 'url', 'file', 'checkbox'] as const;
type FieldType = typeof FIELD_TYPES[number];

type OnboardingField = {
  id: string;
  label: string;
  type: FieldType;
  required: boolean;
  placeholder?: string;
  helperText?: string;
  options?: { label: string; value: string }[];
};

type OnboardingStep = {
  id: string;
  title: string;
  description?: string;
  fields: OnboardingField[];
};

const makeId = (prefix: string) => `${prefix}_${Math.random().toString(36).slice(2, 10)}`;

function makeDefaultStep(idx: number): OnboardingStep {
  return { id: makeId('step'), title: `Step ${idx + 1}`, description: '', fields: [] };
}

export default function CreateOnboardingFlowPage() {
  const navigate = useNavigate();

  const [title, setTitle] = createSignal('');
  const [roleKey, setRoleKey] = createSignal('company');
  const [description, setDescription] = createSignal('');
  const [finalMessage, setFinalMessage] = createSignal('Your onboarding has been submitted for review. We will notify you once it is approved.');
  const [steps, setSteps] = createSignal<OnboardingStep[]>([makeDefaultStep(0), makeDefaultStep(1)]);
  const [saving, setSaving] = createSignal(false);
  const [error, setError] = createSignal('');

  const totalFields = createMemo(() => steps().reduce((sum, s) => sum + s.fields.length, 0));

  const updateStep = (stepId: string, patch: Partial<OnboardingStep>) =>
    setSteps((prev) => prev.map((s) => s.id === stepId ? { ...s, ...patch } : s));

  const addStep = () => setSteps((prev) => [...prev, makeDefaultStep(prev.length)]);

  const removeStep = (stepId: string) => setSteps((prev) => prev.filter((s) => s.id !== stepId));

  const addField = (stepId: string) => {
    const step = steps().find((s) => s.id === stepId)!;
    updateStep(stepId, {
      fields: [...step.fields, { id: makeId('fld'), label: 'New Field', type: 'text', required: false, placeholder: '' }],
    });
  };

  const removeField = (stepId: string, fieldId: string) => {
    const step = steps().find((s) => s.id === stepId)!;
    updateStep(stepId, { fields: step.fields.filter((f) => f.id !== fieldId) });
  };

  const updateField = (stepId: string, fieldId: string, patch: Partial<OnboardingField>) => {
    const step = steps().find((s) => s.id === stepId)!;
    updateStep(stepId, { fields: step.fields.map((f) => f.id === fieldId ? { ...f, ...patch } : f) });
  };

  const handleSubmit = async (status: 'draft' | 'published') => {
    if (!title().trim()) { setError('Flow title is required'); return; }
    if (steps().length === 0) { setError('Add at least one step'); return; }
    try {
      setSaving(true);
      setError('');
      const payload = {
        title: title().trim(),
        roleKey: roleKey(),
        description: description().trim(),
        finalSubmissionMessage: finalMessage(),
        version: 1,
        steps: steps(),
        is_active: status === 'published',
      };
      const res = await fetch(`${API}/api/admin/onboarding-config`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ schema_json: payload, is_active: status === 'published' }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.message || 'Failed to create onboarding flow');
      }
      navigate('/admin/onboarding-schemas');
    } catch (err: any) {
      setError(err.message || 'Failed to create onboarding flow');
    } finally {
      setSaving(false);
    }
  };

  return (
    <AdminShell>
      <div class="page-actions">
        <div>
          <h1 class="page-title">Create Onboarding Flow</h1>
          <p class="page-subtitle">Build one onboarding flow at a time. Start with the role, add steps, then configure fields for each step.</p>
        </div>
        <a class="btn" href="/admin/onboarding-schemas">Back to Onboarding</a>
      </div>

      <Show when={error()}>
        <div class="error-box">{error()}</div>
      </Show>

      {/* Info stats */}
      <div class="onboarding-info-grid">
        <div class="onboarding-stat">
          <div class="stat-label">Role</div>
          <div class="stat-value" style="font-size:14px;margin-top:6px">{roleKey().replace(/_/g, ' ').toUpperCase()}</div>
        </div>
        <div class="onboarding-stat">
          <div class="stat-label">Steps</div>
          <div class="stat-value">{steps().length}</div>
        </div>
        <div class="onboarding-stat">
          <div class="stat-label">Total Fields</div>
          <div class="stat-value">{totalFields()}</div>
        </div>
      </div>

      {/* Flow metadata */}
      <div class="role-form-section">
        <h3>Flow Details</h3>
        <p>Configure the flow title, target role, and final submission message.</p>
        <div class="field-grid-2">
          <div class="field">
            <label>Flow Title <span style="color:#ef4444">*</span></label>
            <input value={title()} onInput={(e) => setTitle(e.currentTarget.value)} placeholder="e.g. Photographer Onboarding" />
          </div>
          <div class="field">
            <label>Target Role</label>
            <select value={roleKey()} onChange={(e) => setRoleKey(e.currentTarget.value)}>
              {EXTERNAL_ROLES.map((r) => <option value={r}>{r.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())}</option>)}
            </select>
          </div>
          <div class="field">
            <label>Description</label>
            <input value={description()} onInput={(e) => setDescription(e.currentTarget.value)} placeholder="Short description of this onboarding flow" />
          </div>
          <div class="field">
            <label>Final Submission Message</label>
            <textarea rows={2} value={finalMessage()} onInput={(e) => setFinalMessage(e.currentTarget.value)} />
          </div>
        </div>
      </div>

      {/* Steps */}
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px">
        <h2 style="margin:0;font-size:18px;font-weight:700">Steps & Fields</h2>
        <button class="btn orange" onClick={addStep}>Add Step</button>
      </div>

      <For each={steps()}>
        {(step, idx) => (
          <div class="step-builder">
            <div class="step-header">
              <div class="step-num">{idx() + 1}</div>
              <input
                class="step-title-input"
                value={step.title}
                onInput={(e) => updateStep(step.id, { title: e.currentTarget.value })}
                placeholder={`Step ${idx() + 1} title`}
              />
              <input
                value={step.description || ''}
                onInput={(e) => updateStep(step.id, { description: e.currentTarget.value })}
                placeholder="Step description (optional)"
                style="border:1px solid #cbd5e1;border-radius:12px;padding:8px 12px;font-size:13px;outline:none;flex:1"
              />
              <button class="btn danger" style="font-size:12px;padding:6px 10px" onClick={() => removeStep(step.id)}>Remove Step</button>
            </div>

            {/* Fields */}
            <div style="margin-top:4px">
              <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
                <p style="margin:0;font-size:13px;font-weight:600;color:#334155">{step.fields.length} field{step.fields.length !== 1 ? 's' : ''}</p>
                <button class="btn orange" style="font-size:12px;padding:5px 10px" onClick={() => addField(step.id)}>Add Field</button>
              </div>

              <For each={step.fields}>
                {(field) => (
                  <div class="field-row">
                    <div style="display:flex;flex-direction:column;gap:4px">
                      <input
                        value={field.label}
                        onInput={(e) => updateField(step.id, field.id, { label: e.currentTarget.value })}
                        placeholder="Field label"
                        style="width:100%"
                      />
                      <input
                        value={field.placeholder || ''}
                        onInput={(e) => updateField(step.id, field.id, { placeholder: e.currentTarget.value })}
                        placeholder="Placeholder text"
                        style="width:100%;font-size:12px"
                      />
                    </div>
                    <select
                      class="field-type-select"
                      value={field.type}
                      onChange={(e) => updateField(step.id, field.id, { type: e.currentTarget.value as FieldType })}
                    >
                      {FIELD_TYPES.map((t) => <option value={t}>{t}</option>)}
                    </select>
                    <label class="checkbox-label" style="justify-content:center">
                      <input
                        type="checkbox"
                        checked={field.required}
                        onChange={(e) => updateField(step.id, field.id, { required: e.currentTarget.checked })}
                      />
                      Required
                    </label>
                    <button class="btn danger" style="font-size:12px;padding:5px 10px" onClick={() => removeField(step.id, field.id)}>✕</button>
                  </div>
                )}
              </For>

              <Show when={step.fields.length === 0}>
                <div style="border:1px dashed #cbd5e1;border-radius:10px;padding:16px;text-align:center;font-size:13px;color:#94a3b8">
                  No fields in this step. Click "Add Field" to add the first field.
                </div>
              </Show>
            </div>
          </div>
        )}
      </For>

      <Show when={steps().length === 0}>
        <div style="border:1px dashed #cbd5e1;border-radius:12px;padding:32px;text-align:center;font-size:13px;color:#94a3b8">
          No steps yet. Click "Add Step" above to get started.
        </div>
      </Show>

      {/* Save actions */}
      <div class="actions" style="justify-content:flex-end;margin-top:16px">
        <button class="btn" onClick={() => handleSubmit('draft')} disabled={saving()}>
          {saving() ? 'Saving...' : 'Save as Draft'}
        </button>
        <button class="btn primary" onClick={() => handleSubmit('published')} disabled={saving()}>
          {saving() ? 'Publishing...' : 'Publish Flow'}
        </button>
      </div>
    </AdminShell>
  );
}
