'use client';

import { motion } from 'framer-motion';
import { useState } from 'react';

type Setting = {
  id: string;
  label: string;
  desc: string;
  default: boolean;
};

const SETTINGS: Setting[] = [
  {
    id: 'alert-80',
    label: 'Alerte à 80 % de consommation tokens',
    desc: 'Reçois un email quand tu approches de ton quota mensuel.',
    default: true,
  },
  {
    id: 'weekly-report',
    label: 'Rapport hebdomadaire de performances',
    desc: 'Résumé SEO chaque lundi matin.',
    default: true,
  },
  {
    id: 'new-features',
    label: 'Nouvelles features produit',
    desc: 'Annonces et mises à jour de la plateforme.',
    default: false,
  },
  {
    id: 'invoices-email',
    label: 'Factures par email',
    desc: "Reçois chaque facture en PDF dès qu'elle est générée.",
    default: true,
  },
];

function Toggle({ checked, onChange }: { checked: boolean; onChange: () => void }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={onChange}
      className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 transition-colors duration-200 focus:outline-none ${
        checked ? 'border-accent bg-accent' : 'border-border bg-bg'
      }`}
    >
      <motion.span
        layout
        transition={{ type: 'spring', stiffness: 500, damping: 35 }}
        className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow-sm mt-px ${
          checked ? 'ml-[14px]' : 'ml-px'
        }`}
      />
    </button>
  );
}

export function NotificationSettings() {
  const [states, setStates] = useState<Record<string, boolean>>(
    Object.fromEntries(SETTINGS.map((s) => [s.id, s.default]))
  );

  const toggle = (id: string) => setStates((prev) => ({ ...prev, [id]: !prev[id] }));

  return (
    <motion.section
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, ease: 'easeOut', delay: 0.25 }}
      className="bg-bg-card border border-border rounded-2xl overflow-hidden"
    >
      <div className="px-6 py-4 border-b border-border">
        <h2 className="text-[15px] font-semibold">Notifications et alertes</h2>
      </div>

      <div className="divide-y divide-border/60">
        {SETTINGS.map((s) => (
          <div key={s.id} className="px-6 py-4 flex items-center gap-4">
            <div className="flex-1 min-w-0">
              <p className="text-[13px] font-medium text-text">{s.label}</p>
              <p className="text-[11.5px] text-text-dim mt-0.5">{s.desc}</p>
            </div>
            <Toggle checked={states[s.id]} onChange={() => toggle(s.id)} />
          </div>
        ))}
      </div>
    </motion.section>
  );
}
