'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Loader2, Save, Lock, Globe, Shield } from 'lucide-react';
import { useChangePassword, useUpdateProfile } from '@/hooks/useUser';
import { useUser } from '@/store/auth.store';
import { cn } from '@/lib/utils';

import Image from 'next/image';
// ── Sections ─────────────────────────────────────────────
const sections = [
  { id: 'profile', label: 'Profil', icon: <Globe className="w-4 h-4" /> },
  { id: 'password', label: 'Password', icon: <Lock className="w-4 h-4" /> },
  { id: 'security', label: 'Verifikasi', icon: <Shield className="w-4 h-4" /> },
];

// ── Profile Schema ─────────────────────────────────────────
const profileSchema = z.object({
  name: z.string().min(1, 'Nama lengkap wajib diisi'),
  phone: z.string().optional(),
});

type ProfileSchema = z.infer<typeof profileSchema>;

// ── Password Schema ───────────────────────────────────────
const passwordSchema = z
  .object({
    current_password: z.string().min(1, 'Password saat ini wajib diisi'),
    password: z.string().min(8, 'Password baru minimal 8 karakter'),
    password_confirmation: z.string().min(1, 'Konfirmasi password wajib diisi'),
  })
  .refine((d) => d.password === d.password_confirmation, {
    message: 'Konfirmasi password tidak cocok',
    path: ['password_confirmation'],
  });

type PasswordSchema = z.infer<typeof passwordSchema>;

// ── Component ─────────────────────────────────────────────
export default function AdminSettingsPage() {
  const [activeSection, setActiveSection] = useState('password');
  const user = useUser();
  const changePassword = useChangePassword();
  const updateProfile = useUpdateProfile();

  const {
    register: registerPassword,
    handleSubmit: handlePasswordSubmit,
    reset: resetPassword,
    formState: { errors: passwordErrors },
  } = useForm<PasswordSchema>({ resolver: zodResolver(passwordSchema) });

  const {
    register: registerProfile,
    handleSubmit: handleProfileSubmit,
    formState: { errors: profileErrors },
  } = useForm<ProfileSchema>({
    resolver: zodResolver(profileSchema),
    values: {
      name: user?.name || '',
      phone: user?.phone || '',
    },
  });

  const onPasswordSubmit = async (data: PasswordSchema) => {
    await changePassword.mutateAsync(data);
    resetPassword();
  };

  const onProfileSubmit = async (data: ProfileSchema) => {
    await updateProfile.mutateAsync(data);
  };

  const inputCls = (hasErr: boolean) =>
    cn(
      'w-full px-3.5 py-2.5 rounded-xl border text-sm bg-white/60 backdrop-blur-sm text-gray-900',
      'focus:outline-none focus:ring-2 transition-all duration-200 shadow-sm',
      hasErr
        ? 'border-red-400 focus:ring-red-500/20 focus:border-red-500'
        : 'border-gray-200 focus:ring-yellow-400/20 focus:border-yellow-400'
    );

  return (
    <div className="min-h-screen bg-transparent text-gray-900 relative overflow-hidden pb-24">
      {/* Background Glow Blobs */}
      <div className="fixed top-0 right-0 w-[500px] h-[500px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />
      <div className="fixed bottom-0 left-0 w-[400px] h-[400px] bg-yellow-400/10 rounded-full blur-[120px] pointer-events-none z-0" />

      <div className="relative z-10 max-w-5xl mx-auto space-y-8 pt-6 px-4 sm:px-6">
        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative"
        >
          <h1 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
            Pengaturan <span className="text-yellow-600">Sistem</span>
          </h1>
          <p className="text-gray-500 text-sm font-medium tracking-wide">
            Kelola preferensi dan keamanan akun Anda.
          </p>

          {/* Mascot decoration */}
          <div className="absolute right-0 -top-8 w-24 md:w-32 opacity-20 pointer-events-none hidden md:block z-0">
            <Image
              src="/mascots/capt-yodi-chill-pose.avif"
              alt="Captain Yodi Mascot"
              className="w-full h-auto object-contain"
              width={500}
              height={500}
            />
          </div>
        </motion.div>

        <div className="grid md:grid-cols-4 gap-8">
          {/* Sidebar nav */}
          <motion.nav
            initial={{ opacity: 0, x: -8 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ delay: 0.05 }}
            className="md:col-span-1 space-y-1"
          >
            {sections.map((s) => (
              <button
                key={s.id}
                onClick={() => setActiveSection(s.id)}
                className={cn(
                  'w-full flex items-center gap-2.5 px-4 py-3 rounded-xl text-sm font-bold transition-all text-left shadow-sm',
                  activeSection === s.id
                    ? 'bg-yellow-400 text-yellow-900 shadow-yellow-400/20'
                    : 'bg-white/40 text-gray-600 hover:bg-white/80 border border-transparent hover:border-gray-200'
                )}
              >
                <span
                  className={
                    activeSection === s.id ? 'text-yellow-900' : 'text-gray-400'
                  }
                >
                  {s.icon}
                </span>
                {s.label}
              </button>
            ))}
          </motion.nav>

          {/* Content */}
          <motion.div
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="md:col-span-3"
          >
            {/* Password Section */}
            {activeSection === 'password' && (
              <div className="bg-white/60 backdrop-blur-xl rounded-3xl border border-gray-200 p-8 shadow-sm">
                <h2 className="text-xl font-black text-gray-900 mb-1">
                  Ubah Password
                </h2>
                <p className="text-sm text-gray-500 mb-6">
                  Pastikan password baru Anda minimal 8 karakter dan mengandung
                  huruf serta angka.
                </p>

                <form
                  onSubmit={handlePasswordSubmit(onPasswordSubmit)}
                  noValidate
                  className="space-y-4"
                >
                  {[
                    {
                      name: 'current_password',
                      label: 'Password Saat Ini',
                      placeholder: '••••••••',
                    },
                    {
                      name: 'password',
                      label: 'Password Baru',
                      placeholder: 'Min. 8 karakter',
                    },
                    {
                      name: 'password_confirmation',
                      label: 'Konfirmasi Password Baru',
                      placeholder: 'Ulangi password baru',
                    },
                  ].map(({ name, label, placeholder }) => (
                    <div key={name}>
                      <label className="block text-sm font-medium text-gray-700 mb-1.5">
                        {label}
                      </label>
                      <input
                        {...registerPassword(name as keyof PasswordSchema)}
                        type="password"
                        placeholder={placeholder}
                        className={inputCls(
                          !!passwordErrors[name as keyof PasswordSchema]
                        )}
                      />
                      {passwordErrors[name as keyof PasswordSchema] && (
                        <p className="mt-1 text-xs text-red-500">
                          {
                            passwordErrors[name as keyof PasswordSchema]
                              ?.message
                          }
                        </p>
                      )}
                    </div>
                  ))}

                  <div className="pt-2">
                    <button
                      type="submit"
                      disabled={changePassword.isPending}
                      className="inline-flex items-center justify-center gap-2 bg-yellow-400 hover:bg-yellow-500 text-yellow-900 text-sm font-bold px-6 py-3 rounded-xl transition-all disabled:opacity-60 disabled:cursor-not-allowed shadow-lg shadow-yellow-400/20"
                    >
                      {changePassword.isPending ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Save className="w-4 h-4" />
                      )}
                      Simpan Password
                    </button>
                  </div>
                </form>
              </div>
            )}

            {activeSection === 'profile' && (
              <div className="bg-white/60 backdrop-blur-xl rounded-3xl border border-gray-200 p-8 shadow-sm">
                <h2 className="text-xl font-black text-gray-900 mb-6">
                  Informasi Profil
                </h2>
                <form
                  onSubmit={handleProfileSubmit(onProfileSubmit)}
                  noValidate
                  className="space-y-4"
                >
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1.5">
                      Nama Lengkap
                    </label>
                    <input
                      {...registerProfile('name')}
                      type="text"
                      placeholder="Nama lengkap"
                      className={inputCls(!!profileErrors.name)}
                    />
                    {profileErrors.name && (
                      <p className="mt-1 text-xs text-red-500">
                        {profileErrors.name.message}
                      </p>
                    )}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1.5">
                      Email
                    </label>
                    <input
                      type="email"
                      value={user?.email || ''}
                      disabled
                      className="w-full px-3.5 py-2.5 rounded-xl border border-gray-200 text-sm bg-gray-50/50 backdrop-blur-sm text-gray-500 cursor-not-allowed shadow-sm"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1.5">
                      Nomor Telepon
                    </label>
                    <input
                      {...registerProfile('phone')}
                      type="text"
                      placeholder="Belum diisi"
                      className={inputCls(!!profileErrors.phone)}
                    />
                    {profileErrors.phone && (
                      <p className="mt-1 text-xs text-red-500">
                        {profileErrors.phone.message}
                      </p>
                    )}
                  </div>

                  <div className="pt-2">
                    <button
                      type="submit"
                      disabled={updateProfile.isPending}
                      className="inline-flex items-center justify-center gap-2 bg-yellow-400 hover:bg-yellow-500 text-yellow-900 text-sm font-bold px-6 py-3 rounded-xl transition-all mt-2 disabled:opacity-60 disabled:cursor-not-allowed shadow-lg shadow-yellow-400/20"
                    >
                      {updateProfile.isPending ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <Save className="w-4 h-4" />
                      )}
                      Simpan Perubahan
                    </button>
                  </div>
                </form>
              </div>
            )}

            {activeSection === 'security' && (
              <div className="bg-white/60 backdrop-blur-xl rounded-3xl border border-gray-200 p-8 space-y-5 shadow-sm">
                <h2 className="text-xl font-black text-gray-900">
                  Verifikasi Email
                </h2>
                <div className="p-4 bg-green-50 rounded-xl border border-green-200">
                  <p className="text-sm font-medium text-green-800">
                    ✓ Email Terverifikasi
                  </p>
                  <p className="text-xs text-green-600 mt-0.5">{user?.email}</p>
                </div>
              </div>
            )}
          </motion.div>
        </div>
      </div>
    </div>
  );
}
