// [REQ F2]  Zarządzanie profilami – edycja danych osobowych i preferencji powiadomień
// [REQ D2]  Zaawansowane formularze – Formik + Zod (toFormikValidationSchema)
// [REQ D4]  React Portals – modal montowany w #portal-root
// [REQ T8]  Obsługa formularzy i walidacja – schemat Zod, błędy inline
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { useFormik } from 'formik';
import { z } from 'zod';
import { toFormikValidationSchema } from 'zod-formik-adapter';
import { X, User, Bell, CheckCircle2 } from 'lucide-react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { API_URL } from '../config';
import styles from './ProfileEditModal.module.scss';

const schema = z.object({
  name:  z.string().min(2, 'Name must be at least 2 characters.'),
  email: z.string().email('Enter a valid email address.'),
});

const TABS = [
  { id: 'profile',       label: 'Profile',       icon: User },
  { id: 'notifications', label: 'Notifications',  icon: Bell },
];

const defaultPrefs = {
  emailOnConfirm:    true,
  emailOnCancelled:  true,
  emailOnReminder:   true,
  emailOnReschedule: true,
  emailOnPromo:      false,
};

const ProfileEditModal = ({ isOpen, onClose }) => {
  const { user, logout } = useAuth();
  const queryClient = useQueryClient();
  const [tab, setTab] = useState('profile');
  const [saved, setSaved] = useState(false);
  const [prefs, setPrefs] = useState(() => ({
    ...defaultPrefs,
    ...(user?.notificationPrefs ?? {}),
  }));

  const { mutate: saveProfile, isPending } = useMutation({
    mutationFn: ({ name, email }) =>
      axios.patch(`${API_URL}/users/${user.id}`, { name, email }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    },
  });

  const { mutate: savePrefs, isPending: prefsPending } = useMutation({
    mutationFn: (notificationPrefs) =>
      axios.patch(`${API_URL}/users/${user.id}`, { notificationPrefs }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setSaved(true);
      setTimeout(() => setSaved(false), 2500);
    },
  });

  const formik = useFormik({
    enableReinitialize: true,
    initialValues: {
      name:  user?.name  ?? '',
      email: user?.email ?? '',
    },
    validationSchema: toFormikValidationSchema(schema),
    onSubmit: (values) => saveProfile(values),
  });

  if (!isOpen) return null;

  const portalRoot = document.getElementById('portal-root') ?? document.body;

  const togglePref = (key) => setPrefs((p) => ({ ...p, [key]: !p[key] }));

  return createPortal(
    <div className={styles['pem']} role="dialog" aria-modal="true" aria-label="Edit profile">
      <div className={styles['pem__overlay']} onClick={onClose} />
      <div className={styles['pem__panel']}>
        {/* Header */}
        <div className={styles['pem__header']}>
          <h2 className={styles['pem__title']}>Account Settings</h2>
          <button className={styles['pem__close']} onClick={onClose} aria-label="Close">
            <X size={18} />
          </button>
        </div>

        {/* Tabs */}
        <div className={styles['pem__tabs']}>
          {TABS.map(({ id, label, icon: Icon }) => (
            <button
              key={id}
              className={[styles['pem__tab'], tab === id ? styles['pem__tab--active'] : ''].join(' ')}
              onClick={() => { setTab(id); setSaved(false); }}
            >
              <Icon size={14} /> {label}
            </button>
          ))}
        </div>

        {saved && (
          <div className={styles['pem__saved']}>
            <CheckCircle2 size={14} /> Saved!
          </div>
        )}

        {/* Profile tab */}
        {tab === 'profile' && (
          <form className={styles['pem__form']} onSubmit={formik.handleSubmit} noValidate>
            <div className={styles['pem__field']}>
              <label className={styles['pem__label']}>Display name</label>
              <input
                className={[styles['pem__input'], formik.touched.name && formik.errors.name ? styles['pem__input--error'] : ''].join(' ')}
                placeholder="John Smith"
                {...formik.getFieldProps('name')}
              />
              {formik.touched.name && formik.errors.name && (
                <p className={styles['pem__error']}>{formik.errors.name}</p>
              )}
            </div>

            <div className={styles['pem__field']}>
              <label className={styles['pem__label']}>Email address</label>
              <input
                type="email"
                className={[styles['pem__input'], formik.touched.email && formik.errors.email ? styles['pem__input--error'] : ''].join(' ')}
                placeholder="you@example.com"
                {...formik.getFieldProps('email')}
              />
              {formik.touched.email && formik.errors.email && (
                <p className={styles['pem__error']}>{formik.errors.email}</p>
              )}
            </div>

            <div className={styles['pem__field']}>
              <label className={styles['pem__label']}>Role</label>
              <input
                className={styles['pem__input']}
                value={user?.role ?? ''}
                disabled
              />
              <p className={styles['pem__hint']}>Role changes require admin approval.</p>
            </div>

            <div className={styles['pem__actions']}>
              <button type="button" className={styles['pem__cancel-btn']} onClick={onClose}>
                Cancel
              </button>
              <button
                type="submit"
                className={styles['pem__save-btn']}
                disabled={isPending || !formik.dirty}
              >
                {isPending ? 'Saving…' : 'Save changes'}
              </button>
            </div>
          </form>
        )}

        {/* Notifications tab */}
        {tab === 'notifications' && (
          <div className={styles['pem__form']}>
            <p className={styles['pem__section-label']}>Email notifications</p>

            {[
              { key: 'emailOnConfirm',    label: 'Booking confirmed',    desc: 'When your reservation is confirmed by staff' },
              { key: 'emailOnCancelled',  label: 'Booking cancelled',    desc: 'When a reservation is cancelled' },
              { key: 'emailOnReminder',   label: 'Reminder 24h before',  desc: 'A reminder email the day before your appointment' },
              { key: 'emailOnReschedule', label: 'Reschedule confirmed', desc: 'When your reservation date or time is changed' },
              { key: 'emailOnPromo',      label: 'Promotions & offers',  desc: 'Occasional news, offers and discounts' },
            ].map(({ key, label, desc }) => (
              <label key={key} className={styles['pem__toggle-row']}>
                <div className={styles['pem__toggle-info']}>
                  <span className={styles['pem__toggle-label']}>{label}</span>
                  <span className={styles['pem__toggle-desc']}>{desc}</span>
                </div>
                <button
                  type="button"
                  role="switch"
                  aria-checked={prefs[key]}
                  className={[styles['pem__switch'], prefs[key] ? styles['pem__switch--on'] : ''].join(' ')}
                  onClick={() => togglePref(key)}
                >
                  <span className={styles['pem__switch-thumb']} />
                </button>
              </label>
            ))}

            <div className={styles['pem__actions']}>
              <button type="button" className={styles['pem__cancel-btn']} onClick={onClose}>
                Cancel
              </button>
              <button
                type="button"
                className={styles['pem__save-btn']}
                disabled={prefsPending}
                onClick={() => savePrefs(prefs)}
              >
                {prefsPending ? 'Saving…' : 'Save preferences'}
              </button>
            </div>
          </div>
        )}
      </div>
    </div>,
    portalRoot
  );
};

export default ProfileEditModal;
