'use client';

import { useEffect } from 'react';
import Image from 'next/image';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { AnimatePresence, motion } from 'framer-motion';
import {
  User,
  Mail,
  Phone,
  MapPin,
  Loader2,
  Save,
  Camera,
  Shield,
  Building2,
  Calendar,
  Hash,
  ChevronDown,
} from 'lucide-react';
import { useUpdateProfile } from '@/hooks/useUser';
import { useUser } from '@/store/auth.store';
import { cn } from '@/lib/utils';
import { Gender } from '@/types';

// ── Schema ─────────────────────────────────────────────────────────────
const profileSchema = z.object({
  name: z.string().min(2, 'Nama minimal 2 karakter').max(100),
  phone: z
    .string()
    .optional()
    .refine(
      (v) => !v || /^(\+62|62|0)[0-9]{8,12}$/.test(v),
      'Format nomor telepon tidak valid'
    ),
  address: z.string().optional(),
  city: z.string().optional(),
  province: z.string().optional(),
  postal_code: z.string().optional(),
  company_name: z.string().optional(),
  date_of_birth: z.string().optional(),
  gender: z.string().optional(),
  distributor_code: z.string().optional(),
  umkm_registration_no: z.string().optional(),
});

type ProfileSchema = z.infer<typeof profileSchema>;

const PROVINCES = [
  'Aceh',
  'Bali',
  'Banten',
  'Bengkulu',
  'DI Yogyakarta',
  'DKI Jakarta',
  'Gorontalo',
  'Jambi',
  'Jawa Barat',
  'Jawa Tengah',
  'Jawa Timur',
  'Kalimantan Barat',
  'Kalimantan Selatan',
  'Kalimantan Tengah',
  'Kalimantan Timur',
  'Kalimantan Utara',
  'Kepulauan Bangka Belitung',
  'Kepulauan Riau',
  'Lampung',
  'Maluku',
  'Maluku Utara',
  'Nusa Tenggara Barat',
  'Nusa Tenggara Timur',
  'Papua',
  'Papua Barat',
  'Riau',
  'Sulawesi Barat',
  'Sulawesi Selatan',
  'Sulawesi Tengah',
  'Sulawesi Tenggara',
  'Sulawesi Utara',
  'Sumatera Barat',
  'Sumatera Selatan',
  'Sumatera Utara',
];

// ── Shared UI Components ───────────────────────────────────────────────
function FieldLabel({
  children,
  required,
  optional,
}: {
  children: React.ReactNode;
  required?: boolean;
  optional?: boolean;
}) {
  return (
    <div className="flex items-center justify-between mb-2">
      <label className="block text-xs font-bold text-gray-600 tracking-wide">
        {children}
        {required && <span className="text-rose-500 ml-1.5">*</span>}
      </label>
      {optional && (
        <span className="text-[9px] font-bold text-gray-500 border border-gray-200 rounded-md px-2 py-0.5 uppercase tracking-widest bg-white">
          Opsional
        </span>
      )}
    </div>
  );
}

function DarkInput({
  icon: Icon,
  error,
  disabled,
  className,
  ...props
}: React.InputHTMLAttributes<HTMLInputElement> & {
  icon?: React.ElementType;
  error?: boolean;
  disabled?: boolean;
}) {
  return (
    <div
      className={cn(
        'relative bg-white/50 border rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm',
        error ? 'border-rose-500 ring-1 ring-rose-500' : 'border-gray-200',
        disabled && 'opacity-50 cursor-not-allowed bg-gray-50'
      )}
    >
      {Icon && (
        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
          <Icon className="w-4 h-4 text-gray-400" />
        </div>
      )}
      <input
        disabled={disabled}
        className={cn(
          'w-full py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none tracking-wide disabled:cursor-not-allowed',
          Icon ? 'pl-11 pr-4' : 'px-4',
          className
        )}
        {...props}
      />
    </div>
  );
}

function DarkSelect({
  icon: Icon,
  children,
  error,
  disabled,
  ...props
}: React.SelectHTMLAttributes<HTMLSelectElement> & {
  icon?: React.ElementType;
  error?: boolean;
  disabled?: boolean;
}) {
  return (
    <div
      className={cn(
        'relative bg-white/50 border rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm',
        error ? 'border-rose-500 ring-1 ring-rose-500' : 'border-gray-200',
        disabled && 'opacity-50 cursor-not-allowed bg-gray-50'
      )}
    >
      {Icon && (
        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
          <Icon className="w-4 h-4 text-gray-400" />
        </div>
      )}
      <select
        disabled={disabled}
        className={cn(
          'w-full py-3.5 bg-transparent text-gray-900 text-sm font-medium focus:outline-none tracking-wide appearance-none cursor-pointer disabled:cursor-not-allowed',
          Icon ? 'pl-11 pr-10' : 'px-4 pr-10',
          '[&>option]:bg-white [&>option]:text-gray-900 [&>option:disabled]:text-gray-400'
        )}
        {...props}
      >
        {children}
      </select>
      <div className="absolute inset-y-0 right-0 pr-4 flex items-center pointer-events-none">
        <ChevronDown className="w-4 h-4 text-gray-400" />
      </div>
    </div>
  );
}

function DarkTextarea({
  error,
  ...props
}: React.TextareaHTMLAttributes<HTMLTextAreaElement> & { error?: boolean }) {
  return (
    <div
      className={cn(
        'relative bg-white/50 border rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm',
        error ? 'border-rose-500 ring-1 ring-rose-500' : 'border-gray-200'
      )}
    >
      <textarea
        className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none tracking-wide resize-none"
        {...props}
      />
    </div>
  );
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p className="mt-2 text-[10px] font-bold text-rose-400 uppercase tracking-widest flex items-center gap-1.5">
      <span className="w-1 h-1 bg-rose-400 rounded-full shrink-0" />
      {message}
    </p>
  );
}

// ── Glass Section ──────────────────────────────────────────────────────
function GlassSection({
  icon: Icon,
  label,
  children,
  delay = 0,
}: {
  icon: React.ElementType;
  label: string;
  children: React.ReactNode;
  delay?: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 12 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.45, ease: [0.22, 1, 0.36, 1] }}
      className="bg-white/60 backdrop-blur-xl border border-white/50 rounded-3xl overflow-hidden shadow-sm"
    >
      <div className="flex items-center gap-3 px-6 sm:px-8 py-5 border-b border-gray-200/50 bg-white/40">
        <div className="p-2 bg-yellow-50 rounded-xl border border-yellow-200 shadow-sm">
          <Icon className="w-4 h-4 text-yellow-600" />
        </div>
        <span className="text-sm font-bold text-gray-900 tracking-wide">
          {label}
        </span>
      </div>
      <div className="p-6 sm:p-8">{children}</div>
    </motion.div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────
export default function UserProfilePage() {
  const user = useUser();
  const updateProfile = useUpdateProfile();

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isDirty },
  } = useForm<ProfileSchema>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      name: '',
      phone: '',
      address: '',
      city: '',
      province: '',
      postal_code: '',
      company_name: '',
      date_of_birth: '',
      gender: '',
      distributor_code: '',
      umkm_registration_no: '',
    },
  });

  useEffect(() => {
    if (user) {
      reset({
        name: user.name,
        phone: user.phone ?? '',
        address: user.profile?.address ?? '',
        city: user.profile?.city ?? '',
        province: user.profile?.province ?? '',
        postal_code: user.profile?.postal_code ?? '',
        company_name: user.profile?.company_name ?? '',
        date_of_birth: user.profile?.date_of_birth ?? '',
        gender: user.profile?.gender ?? '',
        distributor_code: user.profile?.distributor_code ?? '',
        umkm_registration_no: user.profile?.umkm_registration_no ?? '',
      });
    }
  }, [user, reset]);

  const onSubmit = async (data: ProfileSchema) => {
    await updateProfile.mutateAsync({
      name: data.name,
      phone: data.phone,
      address: data.address,
      city: data.city,
      province: data.province,
      postal_code: data.postal_code,
      company_name: data.company_name,
      date_of_birth: data.date_of_birth,
      gender: data.gender as Gender | undefined,
      distributor_code: data.distributor_code,
      umkm_registration_no: data.umkm_registration_no,
    });
    reset(data);
  };

  // Loading skeleton
  if (!user) {
    return (
      <div className="max-w-3xl mx-auto space-y-6 pt-4 relative z-10">
        {[180, 400, 300].map((h, i) => (
          <div
            key={i}
            className="border border-white/5 bg-[#252629]/40 rounded-3xl animate-pulse"
            style={{ height: h }}
          />
        ))}
      </div>
    );
  }

  return (
    <div className="min-h-screen text-gray-900 relative overflow-hidden pb-24">
      <div className="relative z-10 max-w-4xl mx-auto space-y-8 pt-4">
        {/* ── Page title ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <div className="absolute top-0 right-4 pointer-events-none opacity-20 hidden md:block">
            <Image
              src="/mascots/saltu-cooking-pose.avif"
              alt="Saltu"
              className="w-32 h-32 object-contain"
              width={500}
              height={500}
            />
          </div>
          <h2 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2">
            Pengaturan <span className="text-[#FFD738]">Profil</span>
          </h2>
          <p className="text-sm font-medium text-gray-500 tracking-wide">
            Perbarui informasi pribadi dan data alamat Anda
          </p>
        </motion.div>

        <form onSubmit={handleSubmit(onSubmit)} noValidate>
          <div className="space-y-6">
            {/* ── Avatar + Identity Card ── */}
            <motion.div
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.05 }}
              className="bg-white/60 backdrop-blur-xl border border-white/50 rounded-3xl p-6 sm:p-8 flex flex-col sm:flex-row items-center sm:items-start gap-6 shadow-sm"
            >
              {/* Avatar */}
              <div className="relative shrink-0 group">
                <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-full border-2 border-white p-1 bg-white shadow-sm">
                  {user.avatar_url ? (
                    <Image
                      src={user.avatar_url}
                      alt={user.name}
                      width={96}
                      height={96}
                      className="w-full h-full object-cover rounded-full"
                    />
                  ) : (
                    <div className="w-full h-full rounded-full bg-yellow-50 flex items-center justify-center">
                      <User className="w-8 h-8 sm:w-10 sm:h-10 text-yellow-600" />
                    </div>
                  )}
                </div>
                <button
                  type="button"
                  title="Ubah foto"
                  className="absolute bottom-0 right-0 w-8 h-8 bg-white border border-gray-200 rounded-full flex items-center justify-center shadow-md hover:bg-yellow-50 text-gray-600 hover:text-yellow-600 transition-colors"
                >
                  <Camera className="w-4 h-4" />
                </button>
              </div>

              {/* Identity */}
              <div className="flex-1 min-w-0 text-center sm:text-left flex flex-col justify-center h-full sm:pt-2">
                <p className="text-2xl font-black text-gray-900 tracking-tight truncate">
                  {user.name}
                </p>
                <div className="flex flex-col sm:flex-row items-center sm:items-start gap-3 mt-2">
                  <div className="flex items-center gap-1.5 px-3 py-1.5 bg-white border border-gray-200 rounded-lg text-sm text-gray-600 shadow-sm">
                    <Mail className="w-4 h-4 text-gray-400" />
                    <span className="truncate max-w-[200px]">{user.email}</span>
                  </div>
                </div>

                <div className="flex items-center justify-center sm:justify-start gap-2 mt-4 flex-wrap">
                  <span className="text-[10px] font-bold text-yellow-700 border border-yellow-200 bg-yellow-50 px-2.5 py-1 rounded-md uppercase tracking-widest shadow-sm">
                    {user.user_type === 'agen' ? 'Agen Resmi' : 'Member'}
                  </span>
                  {user.is_email_verified && (
                    <span className="text-[10px] font-bold text-emerald-600 border border-emerald-200 bg-emerald-50 px-2.5 py-1 rounded-md uppercase tracking-widest flex items-center gap-1.5 shadow-sm">
                      <Shield className="w-3 h-3" /> Terverifikasi
                    </span>
                  )}
                </div>
              </div>
            </motion.div>

            {/* ── Personal Info ── */}
            <GlassSection icon={User} label="Informasi Pribadi" delay={0.1}>
              <div className="grid sm:grid-cols-2 gap-5">
                <div className="sm:col-span-2">
                  <FieldLabel required>Nama Lengkap</FieldLabel>
                  <DarkInput
                    {...register('name')}
                    type="text"
                    placeholder="Nama Lengkap Anda"
                    error={!!errors.name}
                  />
                  <FieldError message={errors.name?.message} />
                </div>

                <div>
                  <FieldLabel optional>Nomor Telepon</FieldLabel>
                  <DarkInput
                    {...register('phone')}
                    icon={Phone}
                    type="tel"
                    placeholder="08123456789"
                    error={!!errors.phone}
                  />
                  <FieldError message={errors.phone?.message} />
                </div>

                <div>
                  <FieldLabel optional>Tanggal Lahir</FieldLabel>
                  <DarkInput
                    {...register('date_of_birth')}
                    icon={Calendar}
                    type="date"
                    error={!!errors.date_of_birth}
                  />
                </div>

                <div>
                  <FieldLabel optional>Jenis Kelamin</FieldLabel>
                  <DarkSelect {...register('gender')} icon={User}>
                    <option value="">Pilih jenis kelamin</option>
                    <option value="male">Laki-laki</option>
                    <option value="female">Perempuan</option>
                  </DarkSelect>
                </div>

                <div>
                  <FieldLabel optional>Nama Perusahaan (Bila Ada)</FieldLabel>
                  <DarkInput
                    {...register('company_name')}
                    icon={Building2}
                    type="text"
                    placeholder="Nama Toko atau PT"
                  />
                </div>
              </div>
            </GlassSection>

            {/* ── Address ── */}
            <GlassSection icon={MapPin} label="Buku Alamat Utama" delay={0.15}>
              <div className="space-y-5">
                <div>
                  <FieldLabel optional>Alamat Lengkap</FieldLabel>
                  <DarkTextarea
                    {...register('address')}
                    rows={3}
                    placeholder="Nama jalan, gedung, no. rumah, kecamatan..."
                  />
                </div>

                <div className="grid sm:grid-cols-3 gap-5">
                  <div>
                    <FieldLabel optional>Kota / Kabupaten</FieldLabel>
                    <DarkInput
                      {...register('city')}
                      type="text"
                      placeholder="Contoh: Jakarta Selatan"
                    />
                  </div>
                  <div>
                    <FieldLabel optional>Provinsi</FieldLabel>
                    <DarkSelect {...register('province')}>
                      <option value="">Pilih provinsi</option>
                      {PROVINCES.map((p) => (
                        <option key={p} value={p}>
                          {p}
                        </option>
                      ))}
                    </DarkSelect>
                  </div>
                  <div>
                    <FieldLabel optional>Kode Pos</FieldLabel>
                    <DarkInput
                      {...register('postal_code')}
                      type="text"
                      maxLength={5}
                      placeholder="12345"
                    />
                  </div>
                </div>
              </div>
            </GlassSection>

            {/* ── Business info (distributor / umkm) ── */}
            {user.user_type === 'agen' && (
              <GlassSection
                icon={Hash}
                label="Informasi Bisnis & Keagenan"
                delay={0.2}
              >
                <div className="grid sm:grid-cols-2 gap-5">
                  <div>
                    <FieldLabel optional>Kode Distributor</FieldLabel>
                    <DarkInput
                      {...register('distributor_code')}
                      icon={Hash}
                      type="text"
                      placeholder="Contoh: DIST-1002"
                    />
                  </div>
                  <div>
                    <FieldLabel optional>No. Registrasi UMKM</FieldLabel>
                    <DarkInput
                      {...register('umkm_registration_no')}
                      icon={Hash}
                      type="text"
                      placeholder="Contoh: UMKM-102938"
                    />
                  </div>
                </div>
              </GlassSection>
            )}

            {/* ── Submit row ── */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.25 }}
              className="flex flex-col sm:flex-row items-center justify-between gap-4 pt-4"
            >
              <div className="flex items-center gap-2">
                <AnimatePresence>
                  {isDirty && (
                    <motion.div
                      initial={{ opacity: 0, x: -10 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: -10 }}
                      className="flex items-center gap-2 bg-yellow-50 border border-yellow-200 px-3 py-1.5 rounded-lg shadow-sm"
                    >
                      <span className="w-2 h-2 rounded-full bg-yellow-400 animate-pulse" />
                      <span className="text-xs font-bold text-yellow-700">
                        Ada perubahan yang belum disimpan
                      </span>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              <button
                type="submit"
                disabled={updateProfile.isPending || !isDirty}
                className={cn(
                  'w-full sm:w-auto flex items-center justify-center gap-2 px-8 py-3.5 rounded-xl text-sm font-bold tracking-wide transition-all duration-300 shadow-md',
                  isDirty && !updateProfile.isPending
                    ? 'bg-[#FFD738] hover:bg-[#FFD738]/90 text-[#1C1D1F] shadow-[#FFD738]/20'
                    : 'bg-gray-100 text-gray-400 cursor-not-allowed border border-gray-200 shadow-none'
                )}
              >
                {updateProfile.isPending ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                {updateProfile.isPending ? 'Menyimpan...' : 'Simpan Perubahan'}
              </button>
            </motion.div>
          </div>
        </form>
      </div>
    </div>
  );
}
