import {
  mdiAccount,
  mdiCheckCircleOutline,
  mdiChartTimelineVariant,
  mdiHeartPulse,
  mdiLeafCircle,
  mdiTargetVariant,
} from '@mdi/js';
import axios from 'axios';
import Head from 'next/head';
import Link from 'next/link';
import React, { useEffect, useMemo, useState } from 'react';
import type { ReactElement } from 'react';
import BaseButton from '../components/BaseButton';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import NotificationBar from '../components/NotificationBar';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import {
  type ApexOnboardingRecordIds,
  hasCompletedApexOnboarding,
  markApexOnboardingCompleted,
  readApexOnboardingDraft,
  saveApexOnboardingDraft,
} from '../helpers/apexOnboarding';
import { humanize } from '../helpers/humanize';
import LayoutAuthenticated from '../layouts/Authenticated';
import { findMe } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';

type FeedbackState = {
  color: 'success' | 'danger';
  message: string;
} | null;

type PhysicalRecord = {
  id: string;
  height_cm?: number | string | null;
  weight_kg?: number | string | null;
  dominant_hand?: string | null;
  blood_type?: string | null;
  body_frame_size?: string | null;
};

type LifestyleRecord = {
  id: string;
  typical_bedtime?: string | null;
  typical_wake_time?: string | null;
  caffeine_servings_per_day?: number | null;
  avg_daily_steps_estimate?: number | null;
  typical_stress_level?: number | null;
  currently_exercises?: boolean | null;
  diet_pattern?: string | null;
  alcohol_use?: string | null;
  tobacco_nicotine_use?: string | null;
};

type GoalRecord = {
  id: string;
  goal_type?: string | null;
  target_date?: string | null;
  follow_up_answer?: string | null;
};

type ConditionRecord = {
  id: string;
  condition_name?: string | null;
  status?: string | null;
  diagnosing_doctor?: string | null;
  management_plan?: string | null;
};

type OnboardingFormState = {
  firstName: string;
  lastName: string;
  phoneNumber: string;
  email: string;
  heightCm: string;
  weightKg: string;
  dominantHand: string;
  bloodType: string;
  bodyFrameSize: string;
  typicalBedtime: string;
  typicalWakeTime: string;
  caffeineServingsPerDay: string;
  avgDailyStepsEstimate: string;
  typicalStressLevel: string;
  currentlyExercises: string;
  dietPattern: string;
  alcoholUse: string;
  tobaccoNicotineUse: string;
  goalType: string;
  goalTargetDate: string;
  goalFollowUpAnswer: string;
  conditionName: string;
  conditionStatus: string;
  conditionDoctor: string;
  conditionPlan: string;
};

type StepDefinition = {
  key: string;
  title: string;
  eyebrow: string;
  description: string;
  icon: string;
};

const palette = {
  pageBg: '#F5F0E8',
  panelBg: '#FBF7F0',
  panelAlt: '#FFF9F0',
  border: '#E1D6C5',
  borderStrong: '#D6C8B4',
  forest: '#4A6741',
  forestSoft: '#EDF4EA',
  charcoal: '#1C1C1C',
  body: '#4C5544',
  muted: '#7E725E',
  gold: '#C9A84C',
  goldSoft: 'rgba(201,168,76,0.16)',
};

const steps: StepDefinition[] = [
  {
    key: 'identity',
    eyebrow: 'Step 1',
    title: 'Make APEX BRAIN feel personal',
    description: 'Set the name and contact details that will appear throughout your home, reports, and profile.',
    icon: mdiAccount,
  },
  {
    key: 'physical',
    eyebrow: 'Step 2',
    title: 'Capture your body baseline',
    description: 'Start with a few body markers so future trends have context from day one.',
    icon: mdiHeartPulse,
  },
  {
    key: 'lifestyle',
    eyebrow: 'Step 3',
    title: 'Understand your everyday rhythm',
    description: 'Tell the app how you typically sleep, move, and recover so reminders and reviews feel grounded.',
    icon: mdiLeafCircle,
  },
  {
    key: 'goal',
    eyebrow: 'Step 4',
    title: 'Choose your main health focus',
    description: 'Pick one primary goal so Daily Pulse and your deeper modules have a clear north star.',
    icon: mdiTargetVariant,
  },
  {
    key: 'context',
    eyebrow: 'Step 5',
    title: 'Add health context if it matters today',
    description: 'Optional condition notes help your future logs and reports stay clinically useful.',
    icon: mdiChartTimelineVariant,
  },
];

const dominantHandOptions = ['left', 'right', 'ambidextrous'];
const bloodTypeOptions = ['a_plus', 'a_minus', 'b_plus', 'b_minus', 'ab_plus', 'ab_minus', 'o_plus', 'o_minus', 'unknown'];
const bodyFrameOptions = ['small', 'medium', 'large', 'unknown'];
const dietPatternOptions = [
  'omnivore',
  'vegetarian',
  'vegan',
  'pescatarian',
  'keto',
  'paleo',
  'mediterranean',
  'halal',
  'kosher',
  'gluten_free',
  'dairy_free',
  'low_fodmap',
  'other',
];
const alcoholUseOptions = ['never', 'social', 'weekly', 'daily', 'trying_to_quit'];
const tobaccoUseOptions = ['never', 'ex_smoker', 'current_smoker', 'vaper', 'chewing_tobacco'];
const goalTypeOptions = [
  'lose_body_fat',
  'build_muscle_mass',
  'improve_cardiovascular_fitness',
  'increase_flexibility_mobility',
  'improve_sleep_quality',
  'reduce_stress_anxiety',
  'manage_chronic_condition_better',
  'improve_mental_health',
  'optimise_nutrition',
  'improve_gut_health',
  'improve_hormonal_balance',
  'increase_energy_levels',
  'longevity_anti_ageing',
  'athletic_performance',
  'post_surgery_recovery',
  'pregnancy_preparation',
  'postpartum_recovery',
  'improve_sexual_health',
  'improve_fertility',
  'quit_smoking_or_alcohol',
  'build_better_daily_habits',
  'improve_cognitive_performance',
  'support_family_member_health',
];
const conditionStatusOptions = ['active', 'in_remission', 'resolved'];

const moduleLinks = [
  {
    href: '/profile',
    label: 'Profile',
    description: 'Review your personal identity card and account details.',
  },
  {
    href: '/user_physical_baselines/user_physical_baselines-list',
    label: 'Body baseline',
    description: 'See the baseline metrics this setup writes into.',
  },
  {
    href: '/user_lifestyle_baselines/user_lifestyle_baselines-list',
    label: 'Lifestyle baseline',
    description: 'Open your everyday sleep, stress, and habit baseline.',
  },
  {
    href: '/goals/goals-list',
    label: 'Goal vault',
    description: 'Continue shaping your active goals and target dates.',
  },
  {
    href: '/conditions/conditions-list',
    label: 'Conditions',
    description: 'Keep optional condition notes doctor-ready from the start.',
  },
  {
    href: '/daily-pulse',
    label: 'Daily Pulse',
    description: 'Use your newly personalized check-in experience.',
  },
];

function createEmptyForm(email = ''): OnboardingFormState {
  return {
    firstName: '',
    lastName: '',
    phoneNumber: '',
    email,
    heightCm: '',
    weightKg: '',
    dominantHand: '',
    bloodType: '',
    bodyFrameSize: '',
    typicalBedtime: '',
    typicalWakeTime: '',
    caffeineServingsPerDay: '',
    avgDailyStepsEstimate: '',
    typicalStressLevel: '',
    currentlyExercises: '',
    dietPattern: '',
    alcoholUse: '',
    tobaccoNicotineUse: '',
    goalType: '',
    goalTargetDate: '',
    goalFollowUpAnswer: '',
    conditionName: '',
    conditionStatus: '',
    conditionDoctor: '',
    conditionPlan: '',
  };
}

function asString(value: unknown) {
  if (value === null || value === undefined) {
    return '';
  }

  return String(value);
}

function toDateInputValue(value?: string | null) {
  if (!value) {
    return '';
  }

  return value.slice(0, 10);
}

function toYesNoValue(value?: boolean | null) {
  if (value === true) {
    return 'yes';
  }

  if (value === false) {
    return 'no';
  }

  return '';
}

function trimmedValue(value: string) {
  return value.trim();
}

function toNumberOrUndefined(value: string) {
  if (value.trim() === '') {
    return undefined;
  }

  const parsedValue = Number(value);
  return Number.isNaN(parsedValue) ? undefined : parsedValue;
}

async function fetchLatestRecordForUser<T>(endpoint: string, userId: string) {
  const response = await axios.get(
    `/${endpoint}?page=0&limit=1&sort=desc&field=createdAt&user=${userId}`,
  );

  if (!Array.isArray(response.data?.rows)) {
    return null;
  }

  return (response.data.rows[0] ?? null) as T | null;
}

async function fetchRecordById<T>(endpoint: string, id?: string) {
  if (!id) {
    return null;
  }

  const response = await axios.get(`/${endpoint}/${id}`);
  return response.data as T;
}

function entityHasValues(
  payload: Record<string, unknown>,
  ignoredKeys: string[] = ['user', 'is_active'],
) {
  return Object.entries(payload).some(([key, value]) => {
    if (ignoredKeys.includes(key)) {
      return false;
    }

    return value !== undefined && value !== null && value !== '';
  });
}

function FieldError({ error }: { error?: string }) {
  if (!error) {
    return null;
  }

  return <p className="mt-2 text-sm font-medium text-red-600">{error}</p>;
}

export default function OnboardingPage() {
  const dispatch = useAppDispatch();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [activeStep, setActiveStep] = useState(0);
  const [formState, setFormState] = useState<OnboardingFormState>(createEmptyForm());
  const [recordIds, setRecordIds] = useState<ApexOnboardingRecordIds>({});
  const [feedback, setFeedback] = useState<FeedbackState>(null);
  const [fieldErrors, setFieldErrors] = useState<
    Partial<Record<keyof OnboardingFormState, string>>
  >({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [isReadyForAutosave, setIsReadyForAutosave] = useState(false);
  const [draftMeta, setDraftMeta] = useState<{
    lastSavedAt?: string;
    completedAt?: string;
  }>({});

  const completionPercent = Math.round(((activeStep + 1) / steps.length) * 100);
  const hasCompletedOnboarding = Boolean(draftMeta.completedAt) || hasCompletedApexOnboarding(currentUser?.id);

  useEffect(() => {
    if (!currentUser?.id) {
      return;
    }

    let isMounted = true;

    const loadOnboarding = async () => {
      setLoading(true);
      setFeedback(null);
      setIsReadyForAutosave(false);

      const draft = readApexOnboardingDraft<OnboardingFormState>(currentUser.id);
      const draftRecordIds = draft?.recordIds ?? {};

      const defaultState = createEmptyForm(currentUser.email ?? '');
      defaultState.firstName = currentUser.firstName ?? '';
      defaultState.lastName = currentUser.lastName ?? '';
      defaultState.phoneNumber = currentUser.phoneNumber ?? '';

      const loadResults = await Promise.allSettled([
        draftRecordIds.physicalId
          ? fetchRecordById<PhysicalRecord>('user_physical_baselines', draftRecordIds.physicalId)
          : fetchLatestRecordForUser<PhysicalRecord>('user_physical_baselines', currentUser.id),
        draftRecordIds.lifestyleId
          ? fetchRecordById<LifestyleRecord>('user_lifestyle_baselines', draftRecordIds.lifestyleId)
          : fetchLatestRecordForUser<LifestyleRecord>('user_lifestyle_baselines', currentUser.id),
        draftRecordIds.goalId
          ? fetchRecordById<GoalRecord>('goals', draftRecordIds.goalId)
          : Promise.resolve(null),
        draftRecordIds.conditionId
          ? fetchRecordById<ConditionRecord>('conditions', draftRecordIds.conditionId)
          : Promise.resolve(null),
      ]);

      if (!isMounted) {
        return;
      }

      const [physicalResult, lifestyleResult, goalResult, conditionResult] = loadResults;
      const loadErrors = loadResults.filter((result) => result.status === 'rejected');

      if (loadErrors.length) {
        loadErrors.forEach((result) => {
          if (result.status === 'rejected') {
            console.error('Failed to load an onboarding record:', result.reason);
          }
        });

        setFeedback({
          color: 'danger',
          message:
            'We could not load every saved onboarding detail from the server, but you can still continue editing your setup now.',
        });
      }

      const physicalRecord =
        physicalResult.status === 'fulfilled' ? physicalResult.value : null;
      const lifestyleRecord =
        lifestyleResult.status === 'fulfilled' ? lifestyleResult.value : null;
      const goalRecord = goalResult.status === 'fulfilled' ? goalResult.value : null;
      const conditionRecord =
        conditionResult.status === 'fulfilled' ? conditionResult.value : null;

      const nextFormState: OnboardingFormState = {
        ...defaultState,
        heightCm: asString(physicalRecord?.height_cm),
        weightKg: asString(physicalRecord?.weight_kg),
        dominantHand: physicalRecord?.dominant_hand ?? '',
        bloodType: physicalRecord?.blood_type ?? '',
        bodyFrameSize: physicalRecord?.body_frame_size ?? '',
        typicalBedtime: lifestyleRecord?.typical_bedtime ?? '',
        typicalWakeTime: lifestyleRecord?.typical_wake_time ?? '',
        caffeineServingsPerDay: asString(lifestyleRecord?.caffeine_servings_per_day),
        avgDailyStepsEstimate: asString(lifestyleRecord?.avg_daily_steps_estimate),
        typicalStressLevel: asString(lifestyleRecord?.typical_stress_level),
        currentlyExercises: toYesNoValue(lifestyleRecord?.currently_exercises),
        dietPattern: lifestyleRecord?.diet_pattern ?? '',
        alcoholUse: lifestyleRecord?.alcohol_use ?? '',
        tobaccoNicotineUse: lifestyleRecord?.tobacco_nicotine_use ?? '',
        goalType: goalRecord?.goal_type ?? '',
        goalTargetDate: toDateInputValue(goalRecord?.target_date),
        goalFollowUpAnswer: goalRecord?.follow_up_answer ?? '',
        conditionName: conditionRecord?.condition_name ?? '',
        conditionStatus: conditionRecord?.status ?? '',
        conditionDoctor: conditionRecord?.diagnosing_doctor ?? '',
        conditionPlan: conditionRecord?.management_plan ?? '',
        ...(draft?.form ?? {}),
      };

      setFormState(nextFormState);
      setRecordIds({
        physicalId: draftRecordIds.physicalId ?? physicalRecord?.id,
        lifestyleId: draftRecordIds.lifestyleId ?? lifestyleRecord?.id,
        goalId: draftRecordIds.goalId,
        conditionId: draftRecordIds.conditionId,
      });
      setDraftMeta({
        lastSavedAt: draft?.lastSavedAt,
        completedAt: draft?.completedAt,
      });
      setLoading(false);
      setIsReadyForAutosave(true);
    };

    loadOnboarding().catch((error) => {
      console.error('Failed to initialize APEX BRAIN onboarding:', error);

      if (!isMounted) {
        return;
      }

      setFormState({
        ...createEmptyForm(currentUser.email ?? ''),
        firstName: currentUser.firstName ?? '',
        lastName: currentUser.lastName ?? '',
        phoneNumber: currentUser.phoneNumber ?? '',
      });
      setLoading(false);
      setIsReadyForAutosave(true);
      setFeedback({
        color: 'danger',
        message:
          'We hit a setup issue while opening onboarding. You can still complete the form, and any new save will rebuild your draft cleanly.',
      });
    });

    return () => {
      isMounted = false;
    };
  }, [currentUser?.email, currentUser?.firstName, currentUser?.id, currentUser?.lastName, currentUser?.phoneNumber]);

  useEffect(() => {
    if (!isReadyForAutosave || !currentUser?.id) {
      return;
    }

    const timeoutId = window.setTimeout(() => {
      const timestamp = new Date().toISOString();

      saveApexOnboardingDraft<OnboardingFormState>(currentUser.id, {
        form: formState,
        recordIds,
        completedAt: draftMeta.completedAt,
        lastSavedAt: timestamp,
      });

      setDraftMeta((previousState) => ({
        ...previousState,
        lastSavedAt: timestamp,
      }));
    }, 300);

    return () => {
      window.clearTimeout(timeoutId);
    };
  }, [currentUser?.id, draftMeta.completedAt, formState, isReadyForAutosave, recordIds]);

  const filledSections = useMemo(() => {
    return [
      [formState.firstName, formState.lastName, formState.phoneNumber].filter(Boolean)
        .length,
      [
        formState.heightCm,
        formState.weightKg,
        formState.dominantHand,
        formState.bloodType,
        formState.bodyFrameSize,
      ].filter(Boolean).length,
      [
        formState.typicalBedtime,
        formState.typicalWakeTime,
        formState.caffeineServingsPerDay,
        formState.avgDailyStepsEstimate,
        formState.typicalStressLevel,
        formState.currentlyExercises,
        formState.dietPattern,
        formState.alcoholUse,
        formState.tobaccoNicotineUse,
      ].filter(Boolean).length,
      [formState.goalType, formState.goalTargetDate, formState.goalFollowUpAnswer].filter(Boolean)
        .length,
      [
        formState.conditionName,
        formState.conditionStatus,
        formState.conditionDoctor,
        formState.conditionPlan,
      ].filter(Boolean).length,
    ];
  }, [formState]);

  const setupReadiness = useMemo(() => {
    const totalImportantFields = 10;
    const completedImportantFields = [
      formState.firstName,
      formState.heightCm,
      formState.weightKg,
      formState.typicalBedtime,
      formState.typicalWakeTime,
      formState.typicalStressLevel,
      formState.goalType,
      formState.goalTargetDate,
      formState.conditionName,
      formState.conditionPlan,
    ].filter(Boolean).length;

    return Math.round((completedImportantFields / totalImportantFields) * 100);
  }, [formState]);

  const currentStepDefinition = steps[activeStep];

  const handleFieldChange =
    (field: keyof OnboardingFormState) =>
    (
      event: React.ChangeEvent<
        HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
      >,
    ) => {
      const nextValue = event.target.value;

      setFormState((previousState) => ({
        ...previousState,
        [field]: nextValue,
      }));

      setFieldErrors((previousState) => {
        if (!previousState[field]) {
          return previousState;
        }

        const nextErrors = { ...previousState };
        delete nextErrors[field];
        return nextErrors;
      });
    };

  const validateStep = (stepIndex: number) => {
    const nextErrors: Partial<Record<keyof OnboardingFormState, string>> = {};

    if (stepIndex === 0 && !trimmedValue(formState.firstName)) {
      nextErrors.firstName =
        'Please enter the name you want APEX BRAIN to use throughout the app.';
    }

    if (stepIndex === 3 && !formState.goalType) {
      nextErrors.goalType =
        'Choose one primary focus so your home and Daily Pulse can orient around it.';
    }

    return nextErrors;
  };

  const scrollToTop = () => {
    if (typeof window !== 'undefined') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handleNextStep = () => {
    const nextErrors = validateStep(activeStep);

    if (Object.keys(nextErrors).length) {
      setFieldErrors(nextErrors);
      return;
    }

    setFieldErrors({});
    setActiveStep((previousStep) =>
      Math.min(previousStep + 1, steps.length - 1),
    );
    scrollToTop();
  };

  const handlePreviousStep = () => {
    setActiveStep((previousStep) => Math.max(previousStep - 1, 0));
    scrollToTop();
  };

  const handleJumpToStep = (stepIndex: number) => {
    if (stepIndex > activeStep) {
      return;
    }

    setActiveStep(stepIndex);
    scrollToTop();
  };

  const upsertEntity = async (
    endpoint: string,
    payload: Record<string, unknown>,
    existingId?: string,
    createIfMissing = true,
  ) => {
    if (!entityHasValues(payload)) {
      return existingId;
    }

    if (existingId) {
      await axios.put(`/${endpoint}/${existingId}`, {
        id: existingId,
        data: payload,
      });
      return existingId;
    }

    if (!createIfMissing) {
      return undefined;
    }

    const response = await axios.post(`/${endpoint}`, {
      data: payload,
    });

    return response.data?.id as string | undefined;
  };

  const handleSaveOnboarding = async () => {
    const nextErrors = validateStep(activeStep);

    if (Object.keys(nextErrors).length) {
      setFieldErrors(nextErrors);
      return;
    }

    if (!currentUser?.id) {
      setFeedback({
        color: 'danger',
        message:
          'We could not detect your signed-in account. Please refresh the page and try onboarding again.',
      });
      return;
    }

    setSaving(true);
    setFeedback(null);
    setFieldErrors({});

    const nextRecordIds: ApexOnboardingRecordIds = {
      ...recordIds,
    };

    try {
      await axios.put('/auth/profile', {
        profile: {
          firstName: trimmedValue(formState.firstName),
          lastName: trimmedValue(formState.lastName),
          phoneNumber: trimmedValue(formState.phoneNumber),
          email: currentUser.email,
          disabled: Boolean(currentUser.disabled),
          emailVerified: Boolean(currentUser.emailVerified),
          provider: currentUser.provider,
          avatar: currentUser.avatar ?? [],
        },
      });

      const physicalPayload: Record<string, unknown> = {
        user: currentUser.id,
        height_cm: toNumberOrUndefined(formState.heightCm),
        weight_kg: toNumberOrUndefined(formState.weightKg),
        dominant_hand: formState.dominantHand || undefined,
        blood_type: formState.bloodType || undefined,
        body_frame_size: formState.bodyFrameSize || undefined,
      };

      const lifestylePayload: Record<string, unknown> = {
        user: currentUser.id,
        typical_bedtime: trimmedValue(formState.typicalBedtime) || undefined,
        typical_wake_time: trimmedValue(formState.typicalWakeTime) || undefined,
        caffeine_servings_per_day: toNumberOrUndefined(
          formState.caffeineServingsPerDay,
        ),
        avg_daily_steps_estimate: toNumberOrUndefined(
          formState.avgDailyStepsEstimate,
        ),
        typical_stress_level: toNumberOrUndefined(formState.typicalStressLevel),
        currently_exercises:
          formState.currentlyExercises === ''
            ? undefined
            : formState.currentlyExercises === 'yes',
        diet_pattern: formState.dietPattern || undefined,
        alcohol_use: formState.alcoholUse || undefined,
        tobacco_nicotine_use: formState.tobaccoNicotineUse || undefined,
      };

      const goalPayload: Record<string, unknown> = {
        user: currentUser.id,
        goal_type: formState.goalType || undefined,
        target_date: formState.goalTargetDate || undefined,
        follow_up_answer: trimmedValue(formState.goalFollowUpAnswer) || undefined,
        is_active: true,
      };

      const conditionPayload: Record<string, unknown> = {
        user: currentUser.id,
        condition_name: trimmedValue(formState.conditionName) || undefined,
        status: formState.conditionStatus || undefined,
        diagnosing_doctor: trimmedValue(formState.conditionDoctor) || undefined,
        management_plan: trimmedValue(formState.conditionPlan) || undefined,
      };

      nextRecordIds.physicalId = await upsertEntity(
        'user_physical_baselines',
        physicalPayload,
        nextRecordIds.physicalId,
      );
      nextRecordIds.lifestyleId = await upsertEntity(
        'user_lifestyle_baselines',
        lifestylePayload,
        nextRecordIds.lifestyleId,
      );
      nextRecordIds.goalId = await upsertEntity(
        'goals',
        goalPayload,
        nextRecordIds.goalId,
      );
      nextRecordIds.conditionId = await upsertEntity(
        'conditions',
        conditionPayload,
        nextRecordIds.conditionId,
      );

      await dispatch(findMe());

      const completedAt = new Date().toISOString();
      markApexOnboardingCompleted<OnboardingFormState>(currentUser.id, {
        form: formState,
        recordIds: nextRecordIds,
        completedAt,
        lastSavedAt: completedAt,
      });

      setRecordIds(nextRecordIds);
      setDraftMeta({
        completedAt,
        lastSavedAt: completedAt,
      });
      setFeedback({
        color: 'success',
        message:
          'Your APEX BRAIN onboarding is saved. Your profile, baseline, and starting focus are now ready for Daily Pulse and the deeper health modules.',
      });
      setActiveStep(steps.length - 1);
      scrollToTop();
    } catch (error) {
      console.error('Failed to save APEX BRAIN onboarding:', error);
      setFeedback({
        color: 'danger',
        message:
          'We could not finish saving onboarding. Some earlier sections may already be stored, so please review the linked modules below and try again.',
      });
    } finally {
      setSaving(false);
    }
  };

  const renderIdentityStep = () => (
    <>
      <div className="grid gap-6 md:grid-cols-2">
        <div>
          <FormField label="First name" help="This is the name APEX BRAIN will use in greetings and summaries.">
            <input
              name="firstName"
              type="text"
              placeholder="e.g. Maya"
              value={formState.firstName}
              onChange={handleFieldChange('firstName')}
            />
          </FormField>
          <FieldError error={fieldErrors.firstName} />
        </div>

        <FormField label="Last name" help="Optional now — helpful later for formal medical exports.">
          <input
            name="lastName"
            type="text"
            placeholder="e.g. Johnson"
            value={formState.lastName}
            onChange={handleFieldChange('lastName')}
          />
        </FormField>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Phone number" help="Optional now — you can always edit this later.">
          <input
            name="phoneNumber"
            type="tel"
            placeholder="(555) 123-4567"
            value={formState.phoneNumber}
            onChange={handleFieldChange('phoneNumber')}
          />
        </FormField>

        <FormField label="Email" help="This comes from your account and is kept read-only here.">
          <input
            name="email"
            type="email"
            value={formState.email}
            disabled
            onChange={handleFieldChange('email')}
          />
        </FormField>
      </div>
    </>
  );

  const renderPhysicalStep = () => (
    <>
      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Height (cm)" help="A simple starting point for body trend context.">
          <input
            name="heightCm"
            type="number"
            min="0"
            step="0.1"
            placeholder="170"
            value={formState.heightCm}
            onChange={handleFieldChange('heightCm')}
          />
        </FormField>

        <FormField label="Weight (kg)" help="Use your current best estimate — perfection is not required.">
          <input
            name="weightKg"
            type="number"
            min="0"
            step="0.1"
            placeholder="68.5"
            value={formState.weightKg}
            onChange={handleFieldChange('weightKg')}
          />
        </FormField>
      </div>

      <div className="grid gap-6 md:grid-cols-3">
        <FormField label="Dominant hand">
          <select
            name="dominantHand"
            value={formState.dominantHand}
            onChange={handleFieldChange('dominantHand')}
          >
            <option value="">Select one</option>
            {dominantHandOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>

        <FormField label="Blood type">
          <select
            name="bloodType"
            value={formState.bloodType}
            onChange={handleFieldChange('bloodType')}
          >
            <option value="">Select one</option>
            {bloodTypeOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>

        <FormField label="Body frame size">
          <select
            name="bodyFrameSize"
            value={formState.bodyFrameSize}
            onChange={handleFieldChange('bodyFrameSize')}
          >
            <option value="">Select one</option>
            {bodyFrameOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>
      </div>
    </>
  );

  const renderLifestyleStep = () => (
    <>
      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Typical bedtime">
          <input
            name="typicalBedtime"
            type="time"
            value={formState.typicalBedtime}
            onChange={handleFieldChange('typicalBedtime')}
          />
        </FormField>

        <FormField label="Typical wake time">
          <input
            name="typicalWakeTime"
            type="time"
            value={formState.typicalWakeTime}
            onChange={handleFieldChange('typicalWakeTime')}
          />
        </FormField>
      </div>

      <div className="grid gap-6 md:grid-cols-3">
        <FormField label="Caffeine servings / day">
          <input
            name="caffeineServingsPerDay"
            type="number"
            min="0"
            placeholder="2"
            value={formState.caffeineServingsPerDay}
            onChange={handleFieldChange('caffeineServingsPerDay')}
          />
        </FormField>

        <FormField label="Daily step estimate">
          <input
            name="avgDailyStepsEstimate"
            type="number"
            min="0"
            placeholder="7000"
            value={formState.avgDailyStepsEstimate}
            onChange={handleFieldChange('avgDailyStepsEstimate')}
          />
        </FormField>

        <FormField label="Typical stress (1-10)">
          <input
            name="typicalStressLevel"
            type="number"
            min="1"
            max="10"
            placeholder="6"
            value={formState.typicalStressLevel}
            onChange={handleFieldChange('typicalStressLevel')}
          />
        </FormField>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Do you currently exercise?">
          <select
            name="currentlyExercises"
            value={formState.currentlyExercises}
            onChange={handleFieldChange('currentlyExercises')}
          >
            <option value="">Select one</option>
            <option value="yes">Yes</option>
            <option value="no">No</option>
          </select>
        </FormField>

        <FormField label="Diet pattern">
          <select
            name="dietPattern"
            value={formState.dietPattern}
            onChange={handleFieldChange('dietPattern')}
          >
            <option value="">Select one</option>
            {dietPatternOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>
      </div>

      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Alcohol use">
          <select
            name="alcoholUse"
            value={formState.alcoholUse}
            onChange={handleFieldChange('alcoholUse')}
          >
            <option value="">Select one</option>
            {alcoholUseOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>

        <FormField label="Tobacco / nicotine use">
          <select
            name="tobaccoNicotineUse"
            value={formState.tobaccoNicotineUse}
            onChange={handleFieldChange('tobaccoNicotineUse')}
          >
            <option value="">Select one</option>
            {tobaccoUseOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>
      </div>
    </>
  );

  const renderGoalStep = () => (
    <>
      <FormField label="Primary focus" help="Choose the health outcome you most want APEX BRAIN to orient around next.">
        <select
          name="goalType"
          value={formState.goalType}
          onChange={handleFieldChange('goalType')}
        >
          <option value="">Select one</option>
          {goalTypeOptions.map((option) => (
            <option key={option} value={option}>
              {humanize(option)}
            </option>
          ))}
        </select>
      </FormField>
      <FieldError error={fieldErrors.goalType} />

      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Target date" help="Optional, but useful if you want momentum and accountability.">
          <input
            name="goalTargetDate"
            type="date"
            value={formState.goalTargetDate}
            onChange={handleFieldChange('goalTargetDate')}
          />
        </FormField>

        <div
          className="rounded-3xl border p-5"
          style={{
            borderColor: palette.border,
            backgroundColor: palette.panelAlt,
          }}
        >
          <div
            className="text-xs font-semibold uppercase tracking-[0.2em]"
            style={{ color: palette.muted }}
          >
            Why this matters
          </div>
          <p className="mt-3 text-sm leading-7" style={{ color: palette.body }}>
            Your primary focus helps APEX BRAIN move from “generic tracker” to “personal health operating system.” It becomes the lens for your Daily Pulse, reviews, and future recommendations.
          </p>
        </div>
      </div>

      <FormField label="What would success look like?" hasTextareaHeight help="Write it in plain language — the app will save it into your goal record.">
        <textarea
          name="goalFollowUpAnswer"
          rows={5}
          placeholder="Example: Sleep at least 7.5 hours most nights, feel more steady in the afternoon, and stop waking up exhausted."
          value={formState.goalFollowUpAnswer}
          onChange={handleFieldChange('goalFollowUpAnswer')}
        />
      </FormField>
    </>
  );

  const renderContextStep = () => (
    <>
      <div className="grid gap-6 md:grid-cols-2">
        <FormField label="Condition name" help="Optional — add only what feels useful to track now.">
          <input
            name="conditionName"
            type="text"
            placeholder="Example: Migraines"
            value={formState.conditionName}
            onChange={handleFieldChange('conditionName')}
          />
        </FormField>

        <FormField label="Status">
          <select
            name="conditionStatus"
            value={formState.conditionStatus}
            onChange={handleFieldChange('conditionStatus')}
          >
            <option value="">Select one</option>
            {conditionStatusOptions.map((option) => (
              <option key={option} value={option}>
                {humanize(option)}
              </option>
            ))}
          </select>
        </FormField>
      </div>

      <FormField label="Diagnosing doctor">
        <input
          name="conditionDoctor"
          type="text"
          placeholder="Example: Dr. Patel"
          value={formState.conditionDoctor}
          onChange={handleFieldChange('conditionDoctor')}
        />
      </FormField>

      <FormField label="Management plan" hasTextareaHeight help="Optional notes that will make later reports more useful to you or a clinician.">
        <textarea
          name="conditionPlan"
          rows={5}
          placeholder="Example: Track triggers, hydration, sleep consistency, and rescue-med timing."
          value={formState.conditionPlan}
          onChange={handleFieldChange('conditionPlan')}
        />
      </FormField>
    </>
  );

  const renderCurrentStep = () => {
    switch (activeStep) {
      case 0:
        return renderIdentityStep();
      case 1:
        return renderPhysicalStep();
      case 2:
        return renderLifestyleStep();
      case 3:
        return renderGoalStep();
      case 4:
      default:
        return renderContextStep();
    }
  };

  if (loading || !currentUser?.id) {
    return (
      <>
        <Head>
          <title>{getPageTitle('Onboarding')}</title>
        </Head>
        <SectionMain>
          <SectionTitleLineWithButton
            icon={mdiCheckCircleOutline}
            title="Onboarding"
            main
          >
            {''}
          </SectionTitleLineWithButton>
          <CardBox>
            <div className="space-y-3 py-4">
              <div className="text-sm font-semibold uppercase tracking-[0.2em] text-gray-500">
                APEX BRAIN
              </div>
              <h2 className="text-2xl font-semibold text-gray-900">
                Loading your onboarding workspace…
              </h2>
              <p className="text-base leading-7 text-gray-600">
                We’re checking your current account, baseline records, and any saved draft so you can continue where you left off.
              </p>
            </div>
          </CardBox>
        </SectionMain>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Onboarding')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiCheckCircleOutline}
          title="Apex brain onboarding"
          main
        >
          {''}
        </SectionTitleLineWithButton>

        <section
          className="overflow-hidden rounded-[34px] border p-6 shadow-[0_20px_80px_rgba(74,103,65,0.08)] md:p-8"
          style={{
            backgroundColor: palette.pageBg,
            borderColor: palette.border,
          }}
        >
          <div className="grid gap-8 lg:grid-cols-[minmax(0,1.1fr)_320px] lg:items-center">
            <div>
              <div
                className="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-semibold"
                style={{
                  borderColor: palette.borderStrong,
                  backgroundColor: 'rgba(255,255,255,0.64)',
                  color: palette.forest,
                }}
              >
                <BaseIcon path={mdiCheckCircleOutline} size={18} />
                Guided setup for your premium health home
              </div>

              <h2
                className="mt-5 max-w-3xl text-4xl font-semibold tracking-tight"
                style={{ color: palette.charcoal }}
              >
                Let’s turn the schema into a real personal health experience.
              </h2>
              <p
                className="mt-4 max-w-3xl text-lg leading-8"
                style={{ color: palette.body }}
              >
                This first onboarding slice fills in the data that already exists in APEX BRAIN today: your profile basics, body baseline, lifestyle baseline, first active goal, and optional condition context.
              </p>

              <div className="mt-6 h-3 overflow-hidden rounded-full bg-white/70">
                <div
                  className="h-full rounded-full transition-all duration-300"
                  style={{
                    width: `${completionPercent}%`,
                    background:
                      'linear-gradient(90deg, rgba(74,103,65,1) 0%, rgba(201,168,76,1) 100%)',
                  }}
                />
              </div>

              <div className="mt-4 flex flex-wrap items-center gap-3 text-sm font-medium">
                <span style={{ color: palette.forest }}>
                  {currentStepDefinition.eyebrow} of {steps.length}
                </span>
                <span style={{ color: palette.muted }}>•</span>
                <span style={{ color: palette.body }}>{currentStepDefinition.title}</span>
                {hasCompletedOnboarding && (
                  <span
                    className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em]"
                    style={{
                      backgroundColor: palette.forestSoft,
                      color: palette.forest,
                    }}
                  >
                    Baseline saved
                  </span>
                )}
              </div>
            </div>

            <div
              className="rounded-[30px] border p-5"
              style={{
                borderColor: palette.border,
                backgroundColor: 'rgba(255,255,255,0.72)',
              }}
            >
              <div
                className="text-xs font-semibold uppercase tracking-[0.18em]"
                style={{ color: palette.muted }}
              >
                Snapshot
              </div>
              <div className="mt-3 text-3xl font-semibold" style={{ color: palette.charcoal }}>
                {setupReadiness}% ready
              </div>
              <p className="mt-3 text-sm leading-7" style={{ color: palette.body }}>
                You can finish this gradually. APEX BRAIN auto-saves your draft in this browser while you fill things in.
              </p>

              <div className="mt-5 grid grid-cols-2 gap-3">
                {[
                  { label: 'Identity', value: `${filledSections[0]}/3` },
                  { label: 'Body', value: `${filledSections[1]}/5` },
                  { label: 'Lifestyle', value: `${filledSections[2]}/9` },
                  { label: 'Goal', value: `${filledSections[3]}/3` },
                ].map((item) => (
                  <div
                    key={item.label}
                    className="rounded-2xl border p-3"
                    style={{
                      borderColor: palette.border,
                      backgroundColor: palette.panelAlt,
                    }}
                  >
                    <div className="text-xs font-semibold uppercase tracking-[0.16em]" style={{ color: palette.muted }}>
                      {item.label}
                    </div>
                    <div className="mt-2 text-xl font-semibold" style={{ color: palette.charcoal }}>
                      {item.value}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>

        {feedback && (
          <div className="mt-6">
            <NotificationBar
              color={feedback.color}
              icon={feedback.color === 'success' ? mdiCheckCircleOutline : mdiHeartPulse}
              button={
                feedback.color === 'success' ? (
                  <BaseButton href="/daily-pulse" color="whiteDark" label="Open Daily Pulse" />
                ) : undefined
              }
            >
              {feedback.message}
            </NotificationBar>
          </div>
        )}

        <div className="mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
          <CardBox>
            <div className="space-y-8 py-2">
              <div className="flex flex-wrap gap-3">
                {steps.map((step, index) => {
                  const isActive = index === activeStep;
                  const isClickable = index <= activeStep;

                  return (
                    <button
                      key={step.key}
                      type="button"
                      className="min-w-[140px] flex-1 rounded-[24px] border px-4 py-4 text-left transition"
                      style={{
                        borderColor: isActive ? palette.forest : palette.border,
                        backgroundColor: isActive ? palette.forestSoft : palette.panelBg,
                        color: palette.charcoal,
                        cursor: isClickable ? 'pointer' : 'default',
                        opacity: isClickable ? 1 : 0.7,
                      }}
                      onClick={() => handleJumpToStep(index)}
                    >
                      <div className="flex items-center gap-3">
                        <span
                          className="flex h-10 w-10 items-center justify-center rounded-2xl"
                          style={{
                            backgroundColor: isActive ? palette.forest : palette.goldSoft,
                            color: isActive ? palette.pageBg : palette.forest,
                          }}
                        >
                          <BaseIcon path={step.icon} size={20} />
                        </span>
                        <div>
                          <div className="text-xs font-semibold uppercase tracking-[0.16em]" style={{ color: palette.muted }}>
                            {step.eyebrow}
                          </div>
                          <div className="mt-1 text-sm font-semibold leading-5">
                            {step.title}
                          </div>
                        </div>
                      </div>
                    </button>
                  );
                })}
              </div>

              <div>
                <div
                  className="inline-flex items-center gap-2 rounded-full px-3 py-2 text-xs font-semibold uppercase tracking-[0.18em]"
                  style={{
                    backgroundColor: palette.goldSoft,
                    color: palette.forest,
                  }}
                >
                  <BaseIcon path={currentStepDefinition.icon} size={16} />
                  {currentStepDefinition.eyebrow}
                </div>
                <h3 className="mt-4 text-3xl font-semibold" style={{ color: palette.charcoal }}>
                  {currentStepDefinition.title}
                </h3>
                <p className="mt-3 max-w-3xl text-base leading-7" style={{ color: palette.body }}>
                  {currentStepDefinition.description}
                </p>
              </div>

              <div
                className="rounded-[30px] border p-6"
                style={{
                  borderColor: palette.border,
                  backgroundColor: palette.panelBg,
                }}
              >
                {renderCurrentStep()}
              </div>

              <div className="flex flex-col gap-4 border-t pt-6 md:flex-row md:items-center md:justify-between" style={{ borderColor: palette.border }}>
                <div className="text-sm leading-7" style={{ color: palette.body }}>
                  {draftMeta.lastSavedAt ? (
                    <>
                      Draft last saved in this browser on{' '}
                      <span className="font-semibold" style={{ color: palette.charcoal }}>
                        {new Date(draftMeta.lastSavedAt).toLocaleString()}
                      </span>
                      .
                    </>
                  ) : (
                    'Your onboarding draft will auto-save in this browser as you go.'
                  )}
                </div>

                <div className="flex flex-wrap gap-3">
                  {activeStep > 0 && (
                    <BaseButton
                      type="button"
                      color="whiteDark"
                      label="Back"
                      onClick={handlePreviousStep}
                    />
                  )}

                  {activeStep < steps.length - 1 ? (
                    <BaseButton
                      type="button"
                      color="info"
                      label="Continue"
                      onClick={handleNextStep}
                    />
                  ) : (
                    <BaseButton
                      type="button"
                      color="success"
                      label={saving ? 'Saving...' : 'Save onboarding'}
                      disabled={saving}
                      onClick={handleSaveOnboarding}
                    />
                  )}
                </div>
              </div>
            </div>
          </CardBox>

          <div className="space-y-6">
            <CardBox>
              <div className="space-y-4 py-2">
                <div className="flex items-center gap-3">
                  <span
                    className="flex h-12 w-12 items-center justify-center rounded-2xl"
                    style={{
                      backgroundColor: palette.forestSoft,
                      color: palette.forest,
                    }}
                  >
                    <BaseIcon path={mdiCheckCircleOutline} size={24} />
                  </span>
                  <div>
                    <div className="text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: palette.muted }}>
                      What this setup powers
                    </div>
                    <div className="mt-1 text-xl font-semibold" style={{ color: palette.charcoal }}>
                      Your first real APEX BRAIN home
                    </div>
                  </div>
                </div>

                <p className="text-sm leading-7" style={{ color: palette.body }}>
                  This onboarding doesn’t live in isolation — it writes into the real app modules that already exist today. That means your first setup can immediately feed Daily Pulse, profile reviews, and the deeper admin screens behind the scenes.
                </p>

                <div className="space-y-3">
                  {moduleLinks.map((link) => (
                    <Link
                      key={link.href}
                      href={link.href}
                      className="block rounded-[24px] border p-4 transition hover:-translate-y-0.5"
                      style={{
                        borderColor: palette.border,
                        backgroundColor: palette.panelAlt,
                      }}
                    >
                      <div className="flex items-center justify-between gap-3">
                        <div>
                          <div className="text-sm font-semibold" style={{ color: palette.charcoal }}>
                            {link.label}
                          </div>
                          <div className="mt-1 text-sm leading-6" style={{ color: palette.body }}>
                            {link.description}
                          </div>
                        </div>
                        <span className="text-lg font-semibold" style={{ color: palette.forest }}>
                          →
                        </span>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            </CardBox>

            <CardBox>
              <div className="space-y-4 py-2">
                <div className="text-xs font-semibold uppercase tracking-[0.18em]" style={{ color: palette.muted }}>
                  Your current focus
                </div>
                <div className="rounded-[26px] border p-5" style={{ borderColor: palette.border, backgroundColor: palette.panelAlt }}>
                  <div className="text-sm font-semibold" style={{ color: palette.charcoal }}>
                    {trimmedValue(formState.firstName) || 'Your profile'}
                  </div>
                  <p className="mt-2 text-sm leading-7" style={{ color: palette.body }}>
                    {formState.goalType
                      ? `${humanize(formState.goalType)} is currently your headline goal.`
                      : 'Choose a primary focus and it will become the anchor for your early APEX BRAIN experience.'}
                  </p>
                </div>

                <div className="rounded-[26px] border p-5" style={{ borderColor: palette.border, backgroundColor: palette.panelAlt }}>
                  <div className="text-sm font-semibold" style={{ color: palette.charcoal }}>
                    Daily rhythm snapshot
                  </div>
                  <ul className="mt-3 space-y-2 text-sm leading-7" style={{ color: palette.body }}>
                    <li>
                      Sleep window:{' '}
                      <span className="font-semibold" style={{ color: palette.charcoal }}>
                        {formState.typicalBedtime || '--:--'} → {formState.typicalWakeTime || '--:--'}
                      </span>
                    </li>
                    <li>
                      Stress level:{' '}
                      <span className="font-semibold" style={{ color: palette.charcoal }}>
                        {formState.typicalStressLevel || 'Not set'}
                      </span>
                    </li>
                    <li>
                      Movement:{' '}
                      <span className="font-semibold" style={{ color: palette.charcoal }}>
                        {formState.currentlyExercises
                          ? humanize(formState.currentlyExercises)
                          : 'Not set'}
                      </span>
                    </li>
                  </ul>
                </div>

                <div className="rounded-[26px] border p-5" style={{ borderColor: palette.border, backgroundColor: palette.panelAlt }}>
                  <div className="text-sm font-semibold" style={{ color: palette.charcoal }}>
                    Why this is a first slice
                  </div>
                  <p className="mt-2 text-sm leading-7" style={{ color: palette.body }}>
                    APEX BRAIN’s schema is already broad, but this onboarding flow is the first consumer-friendly layer on top of it. Next we can expand it into deeper medical history, family setup, reproductive health, care-team collaboration, and more guided dashboards.
                  </p>
                </div>
              </div>
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
}

OnboardingPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};
