/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { motion } from 'framer-motion';
import {
  ArrowLeft,
  Loader2,
  MapPin,
  User,
  Phone,
  Hash,
  ChevronDown,
  CheckCircle2,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAddAddress } from '@/hooks/useAddress';
import { LOCATION_DATA } from '@/lib/constants/checkout';

import Image from 'next/image';
const addressSchema = z.object({
  label: z.string().min(1, 'Label wajib diisi (contoh: Rumah, Kantor)'),
  recipient_name: z.string().min(2, 'Nama penerima minimal 2 karakter'),
  phone: z.string().min(9, 'Nomor telepon tidak valid'),
  province: z.string().min(1, 'Provinsi wajib dipilih'),
  city: z.string().min(1, 'Kota/Kabupaten wajib dipilih'),
  district: z.string().min(1, 'Kecamatan wajib diisi'),
  village: z.string().min(1, 'Desa/Kelurahan wajib diisi'),
  postal_code: z.string().min(3, 'Kode pos wajib diisi'),
  address: z.string().min(10, 'Alamat lengkap wajib diisi secara detail'),
  is_primary: z.boolean(),
});

type AddressFormValues = z.infer<typeof addressSchema>;

function FieldLabel({
  children,
  required,
}: {
  children: React.ReactNode;
  required?: boolean;
}) {
  return (
    <label className="block text-xs font-bold text-gray-400 mb-2 tracking-wide">
      {children}
      {required && <span className="text-rose-500 ml-1.5">*</span>}
    </label>
  );
}

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>
  );
}

// ── Page Component ─────────────────────────────────────────────────────
export default function AddUserAddressPage() {
  const router = useRouter();
  const addMutation = useAddAddress();

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<AddressFormValues>({
    resolver: zodResolver(addressSchema),
    defaultValues: {
      label: '',
      recipient_name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      village: '',
      postal_code: '',
      address: '',
      is_primary: false,
    },
  });

  // eslint-disable-next-line react-hooks/incompatible-library
  const selectedProv = watch('province');
  const selectedCity = watch('city');
  const selectedDist = watch('district');

  const availableCities = selectedProv
    ? LOCATION_DATA.cities[selectedProv] || []
    : [];
  const availableDistricts = selectedCity
    ? LOCATION_DATA.districts[selectedCity] || []
    : [];
  const availableVillages = selectedDist
    ? LOCATION_DATA.villages[selectedDist] || []
    : [];

  const onSubmit = (data: AddressFormValues) => {
    const payload = { ...data };

    addMutation.mutate(payload, {
      onSuccess: () => {
        router.push('/dashboard/user/addresses');
      },
    });
  };

  return (
    <div className="min-h-screen text-gray-900 relative overflow-hidden pb-24">
      <div className="relative z-10 max-w-3xl mx-auto px-4 sm:px-6 pt-10 sm:pt-12 space-y-8">
        {/* ── Header ── */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          className="relative z-20"
        >
          <div className="absolute top-0 right-10 pointer-events-none opacity-20 hidden md:block z-0">
            <Image
              src="/mascots/family-hug.avif"
              alt="Family Hug Mascot"
              className="w-32 h-32 object-contain rounded-full"
              width={500}
              height={500}
            />
          </div>
          <Link
            href="/dashboard/user/addresses"
            className="inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-white/60 backdrop-blur-md border border-gray-200 text-xs font-bold text-gray-500 hover:bg-yellow-50 hover:border-yellow-200 hover:text-yellow-600 transition-all mb-6 group shadow-sm relative z-10"
          >
            <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />{' '}
            Kembali ke Buku Alamat
          </Link>

          <h2 className="text-3xl sm:text-4xl font-black text-gray-900 tracking-tight leading-none mb-2 relative z-10">
            Tambah <span className="text-[#FFD738]">Alamat</span>
          </h2>
          <p className="text-sm font-medium text-gray-500 tracking-wide relative z-10">
            Simpan alamat baru untuk mempercepat proses pesanan di masa
            mendatang.
          </p>
        </motion.div>

        {/* ── Form Section ── */}
        <motion.form
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1 }}
          onSubmit={handleSubmit(onSubmit)}
          className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-3xl overflow-hidden shadow-sm"
          noValidate
        >
          <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 border border-yellow-200 rounded-xl shadow-sm">
              <MapPin className="w-4 h-4 text-yellow-600" />
            </div>
            <span className="text-sm font-bold text-gray-900 tracking-wide">
              Detail Alamat Baru
            </span>
          </div>

          <div className="p-6 sm:p-8 space-y-6">
            <div className="grid sm:grid-cols-2 gap-6">
              <div className="sm:col-span-2">
                <FieldLabel required>Alamat Lengkap</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
                  <textarea
                    {...register('address')}
                    rows={3}
                    placeholder="Nama jalan, gedung, no. rumah, detail patokan..."
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none resize-none"
                  />
                </div>
                <FieldError message={errors.address?.message} />
              </div>

              <div className="sm:col-span-2">
                <FieldLabel required>Label Alamat</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 transition-all shadow-sm">
                  <select
                    {...register('label')}
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium appearance-none outline-none"
                  >
                    <option value="" className="bg-white text-gray-400">
                      Pilih label alamat
                    </option>
                    <option value="Rumah" className="bg-white text-gray-900">
                      Rumah
                    </option>
                    <option value="Kantor" className="bg-white text-gray-900">
                      Kantor
                    </option>
                    <option value="Kos" className="bg-white text-gray-900">
                      Kos
                    </option>
                    <option
                      value="Apartemen"
                      className="bg-white text-gray-900"
                    >
                      Apartemen
                    </option>
                    <option value="Lainnya" className="bg-white text-gray-900">
                      Lainnya
                    </option>
                  </select>
                  <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
                <FieldError message={errors.label?.message} />
              </div>

              <div>
                <FieldLabel required>Nama Penerima</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
                  <User className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    {...register('recipient_name')}
                    placeholder="Nama lengkap"
                    className="w-full pl-11 pr-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none"
                  />
                </div>
                <FieldError message={errors.recipient_name?.message} />
              </div>

              <div>
                <FieldLabel required>Nomor Telepon</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
                  <Phone className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    {...register('phone')}
                    type="tel"
                    placeholder="08XXXXXXXXXX"
                    className="w-full pl-11 pr-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none"
                  />
                </div>
                <FieldError message={errors.phone?.message} />
              </div>

              <div>
                <FieldLabel required>Provinsi</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 transition-all shadow-sm">
                  <select
                    {...register('province', {
                      onChange: () => {
                        setValue('city', '');
                        setValue('district', '');
                        setValue('village', '');
                        setValue('postal_code', '');
                      },
                    })}
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium appearance-none outline-none"
                  >
                    <option value="" className="bg-white text-gray-400">
                      Pilih provinsi
                    </option>
                    {LOCATION_DATA.provinces.map((p: string) => (
                      <option
                        key={p}
                        value={p}
                        className="bg-white text-gray-900"
                      >
                        {p}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
                <FieldError message={errors.province?.message} />
              </div>

              <div>
                <FieldLabel required>Kota / Kabupaten</FieldLabel>
                <div
                  className={cn(
                    'relative border rounded-xl transition-all shadow-sm',
                    selectedProv
                      ? 'bg-white border-gray-200 focus-within:border-yellow-400'
                      : 'bg-gray-50 border-gray-200 opacity-50'
                  )}
                >
                  <select
                    {...register('city', {
                      onChange: () => {
                        setValue('district', '');
                        setValue('village', '');
                        setValue('postal_code', '');
                      },
                    })}
                    disabled={!selectedProv}
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium appearance-none outline-none disabled:cursor-not-allowed"
                  >
                    <option value="" className="bg-white text-gray-400">
                      {selectedProv ? 'Pilih kota' : 'Pilih provinsi dahulu'}
                    </option>
                    {availableCities.map((c: string) => (
                      <option
                        key={c}
                        value={c}
                        className="bg-white text-gray-900"
                      >
                        {c}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
                <FieldError message={errors.city?.message} />
              </div>

              <div>
                <FieldLabel required>Kecamatan</FieldLabel>
                <div
                  className={cn(
                    'relative border rounded-xl transition-all shadow-sm',
                    selectedCity
                      ? 'bg-white border-gray-200 focus-within:border-yellow-400'
                      : 'bg-gray-50 border-gray-200 opacity-50'
                  )}
                >
                  <select
                    {...register('district', {
                      onChange: () => {
                        setValue('village', '');
                        setValue('postal_code', '');
                      },
                    })}
                    disabled={!selectedCity}
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium appearance-none outline-none disabled:cursor-not-allowed"
                  >
                    <option value="" className="bg-white text-gray-400">
                      {selectedCity ? 'Pilih kecamatan' : 'Pilih kota dahulu'}
                    </option>
                    {availableDistricts.map((d: string) => (
                      <option
                        key={d}
                        value={d}
                        className="bg-white text-gray-900"
                      >
                        {d}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
                <FieldError message={errors.district?.message} />
              </div>

              <div>
                <FieldLabel>Kelurahan (Auto-Kode Pos)</FieldLabel>
                <div
                  className={cn(
                    'relative border rounded-xl transition-all shadow-sm',
                    selectedDist
                      ? 'bg-white border-gray-200 focus-within:border-yellow-400'
                      : 'bg-gray-50 border-gray-200 opacity-50'
                  )}
                >
                  <select
                    {...register('village', {
                      onChange: (e) => {
                        const v = availableVillages.find(
                          (x: any) => x.name === e.target.value
                        );
                        if (v) setValue('postal_code', v.zip);
                      },
                    })}
                    disabled={!selectedDist}
                    className="w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium appearance-none outline-none disabled:cursor-not-allowed"
                  >
                    <option value="" className="bg-white text-gray-400">
                      {selectedDist
                        ? 'Pilih kelurahan'
                        : 'Pilih kecamatan dahulu'}
                    </option>
                    {availableVillages.map((v: any) => (
                      <option
                        key={v.name}
                        value={v.name}
                        className="bg-white text-gray-900"
                      >
                        {v.name}
                      </option>
                    ))}
                  </select>
                  <ChevronDown className="absolute right-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                </div>
              </div>

              <div className="sm:col-span-2">
                <FieldLabel required>Kode Pos</FieldLabel>
                <div className="relative bg-white border border-gray-200 rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm">
                  <Hash className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    {...register('postal_code')}
                    placeholder="Kode Pos"
                    className="w-full pl-11 pr-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium placeholder:text-gray-400 focus:outline-none"
                  />
                </div>
                <FieldError message={errors.postal_code?.message} />
              </div>
            </div>
          </div>

          <div className="px-6 sm:px-8 py-5 border-t border-gray-200/50 bg-white/40 flex flex-col sm:flex-row items-center justify-between gap-6">
            {/* Toggle Primary */}
            <label className="flex items-center gap-3 cursor-pointer group w-full sm:w-auto">
              <div className="relative flex items-center justify-center w-6 h-6 border-2 border-gray-300 rounded-md bg-white group-hover:border-yellow-400 transition-all overflow-hidden shadow-sm">
                <input
                  type="checkbox"
                  {...register('is_primary')}
                  className="peer sr-only"
                />
                <CheckCircle2 className="w-5 h-5 text-yellow-500 opacity-0 peer-checked:opacity-100 transition-opacity absolute" />
              </div>
              <div>
                <p className="text-sm font-bold text-gray-900">
                  Jadikan Alamat Utama
                </p>
                <p className="text-[10px] text-gray-500 uppercase tracking-widest mt-0.5">
                  Otomatis dipilih saat checkout
                </p>
              </div>
            </label>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={addMutation.isPending}
              className="w-full sm:w-auto px-8 py-3.5 rounded-xl bg-[#FFD738] hover:bg-[#FFD738]/90 text-[#1C1D1F] text-sm font-bold uppercase tracking-wider flex items-center justify-center gap-2 transition-all shadow-lg shadow-[#FFD738]/20 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {addMutation.isPending ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" /> Menyimpan...
                </>
              ) : (
                'Simpan Alamat'
              )}
            </button>
          </div>
        </motion.form>
      </div>
    </div>
  );
}
