'use client';

import React, { useEffect } from 'react';
import { motion } from 'framer-motion';
import { cn, formatIDR } from '@/lib/utils';
import { Loader2, Tag, Check } from 'lucide-react';
import { RewardService, UserVoucher } from '@/lib/services/reward.service';

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

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

export const DarkSelect = React.forwardRef<
  HTMLSelectElement,
  React.SelectHTMLAttributes<HTMLSelectElement> & { error?: boolean }
>(({ error, children, className, ...props }, ref) => {
  return (
    <div
      className={cn(
        'relative bg-white border rounded-xl focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400 transition-all shadow-sm',
        error ? 'border-rose-300 ring-1 ring-rose-300' : 'border-gray-200'
      )}
    >
      <select
        ref={ref}
        className={cn(
          'w-full px-4 py-3.5 bg-transparent text-gray-900 text-sm font-medium focus:outline-none appearance-none tracking-wide cursor-pointer',
          className
        )}
        {...props}
      >
        {children}
      </select>
      <div className="absolute inset-y-0 right-0 pr-4 flex items-center pointer-events-none">
        <svg
          className="w-4 h-4 text-gray-400"
          viewBox="0 0 20 20"
          fill="currentColor"
        >
          <path
            fillRule="evenodd"
            d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
            clipRule="evenodd"
          />
        </svg>
      </div>
    </div>
  );
});
DarkSelect.displayName = 'DarkSelect';

export 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: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay, duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
      className="bg-white/60 backdrop-blur-xl border border-gray-200 rounded-2xl sm:rounded-3xl p-5 sm:p-6 lg:p-8 relative overflow-hidden shadow-sm"
    >
      <div className="flex items-center gap-3 mb-5 sm:mb-6 relative z-10">
        <div className="p-2.5 bg-yellow-50 border border-yellow-200 rounded-xl shadow-sm">
          <Icon className="w-5 h-5 text-yellow-600" />
        </div>
        <h2 className="text-base font-bold text-gray-900 tracking-wide">
          {label}
        </h2>
      </div>
      <div className="relative z-10">{children}</div>
    </motion.div>
  );
}

export function PaymentCard({
  pm,
  checked,
  register,
}: {
  pm: { value: string; label: string; desc: string };
  checked: boolean;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  register: any;
}) {
  return (
    <label
      className={cn(
        'relative flex items-start gap-4 p-4 rounded-2xl border transition-all cursor-pointer group',
        checked
          ? 'bg-yellow-50/50 border-yellow-400 ring-1 ring-yellow-400'
          : 'bg-white border-gray-200 hover:border-yellow-400/50 hover:bg-yellow-50/20'
      )}
    >
      <input
        type="radio"
        value={pm.value}
        className="mt-1 sr-only"
        {...register('payment_method')}
      />
      <div
        className={cn(
          'w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 mt-0.5 transition-colors',
          checked
            ? 'border-yellow-500'
            : 'border-gray-300 group-hover:border-yellow-400'
        )}
      >
        {checked && <div className="w-2.5 h-2.5 rounded-full bg-yellow-500" />}
      </div>
      <div>
        <p
          className={cn(
            'text-sm font-bold tracking-wide transition-colors',
            checked ? 'text-gray-900' : 'text-gray-700'
          )}
        >
          {pm.label}
        </p>
        <p className="text-[10px] text-gray-500 font-medium tracking-wide mt-0.5">
          {pm.desc}
        </p>
      </div>
    </label>
  );
}

export function CouponInput({
  applied,
  onApply,
  onRemove,
  isPending,
}: {
  applied: string | null;
  onApply: (code: string) => void;
  onRemove: () => void;
  isPending: boolean;
}) {
  const [code, setCode] = React.useState('');
  const [vouchers, setVouchers] = React.useState<UserVoucher[]>([]);
  const [loadingVouchers, setLoadingVouchers] = React.useState(true);

  useEffect(() => {
    RewardService.getVouchers()
      .then((res) => {
        setVouchers(res.data.filter((v) => v.status === 'ACTIVE'));
      })
      .catch((err) => console.error(err))
      .finally(() => setLoadingVouchers(false));
  }, []);

  return (
    <div className="relative flex flex-col gap-4">
      <div
        className={cn(
          'relative flex items-center bg-white border rounded-xl overflow-hidden shadow-sm transition-all',
          applied
            ? 'border-green-400 ring-1 ring-green-400 bg-green-50/30'
            : 'border-gray-200 focus-within:border-yellow-400 focus-within:ring-1 focus-within:ring-yellow-400'
        )}
      >
        <div className="pl-4">
          <Tag
            className={cn(
              'w-4 h-4',
              applied ? 'text-green-500' : 'text-gray-400'
            )}
          />
        </div>
        <input
          type="text"
          value={applied ? applied : code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="Masukkan kode promo"
          disabled={!!applied || isPending}
          className="flex-1 px-3 py-3.5 bg-transparent text-sm font-bold text-gray-900 placeholder-gray-400 focus:outline-none disabled:opacity-100 uppercase tracking-widest"
        />
        <div className="pr-2">
          {applied ? (
            <button
              type="button"
              onClick={onRemove}
              disabled={isPending}
              className="px-4 py-2 text-xs font-bold text-rose-500 hover:bg-rose-50 rounded-lg transition-colors"
            >
              Hapus
            </button>
          ) : (
            <button
              type="button"
              onClick={() => {
                if (code.trim()) onApply(code);
              }}
              disabled={!code.trim() || isPending}
              className="px-4 py-2 text-xs font-bold text-gray-900 bg-yellow-400 hover:bg-yellow-500 disabled:opacity-50 disabled:bg-gray-100 disabled:text-gray-400 rounded-lg transition-colors flex items-center gap-2 shadow-sm"
            >
              {isPending && <Loader2 className="w-3 h-3 animate-spin" />}
              Terapkan
            </button>
          )}
        </div>
      </div>
      {applied && (
        <motion.p
          initial={{ opacity: 0, y: -5 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-[10px] font-bold text-green-600 uppercase tracking-widest flex items-center gap-1.5 ml-1"
        >
          <span className="w-1 h-1 rounded-full bg-green-500" />
          Kupon berhasil dipasang!
        </motion.p>
      )}

      {!applied && (
        <div className="flex flex-col gap-2">
          <div className="flex items-center justify-between mb-1">
            <p className="text-[10px] font-bold text-gray-500 uppercase tracking-widest">
              Atau Pilih Kupon Anda:
            </p>
            {loadingVouchers && (
              <Loader2 className="w-3 h-3 text-gray-400 animate-spin" />
            )}
          </div>
          <div className="flex flex-col gap-2.5">
            {!loadingVouchers && vouchers.length === 0 ? (
              <div className="text-center p-4 border border-dashed border-gray-200 rounded-xl bg-gray-50">
                <p className="text-xs text-gray-500">
                  Anda belum memiliki kupon aktif.
                </p>
              </div>
            ) : (
              vouchers.map((voucher) => (
                <button
                  type="button"
                  key={voucher.id}
                  onClick={() => {
                    setCode(voucher.code);
                    onApply(voucher.code);
                  }}
                  disabled={isPending}
                  className="flex items-center justify-between p-3 border border-gray-200 rounded-xl hover:border-yellow-400 hover:bg-yellow-50/50 transition-all group disabled:opacity-50 text-left bg-white shadow-sm cursor-pointer"
                >
                  <div>
                    <p className="text-xs font-bold text-gray-900 tracking-wide group-hover:text-yellow-700 transition-colors">
                      {voucher.code}
                    </p>
                    <p className="text-[10px] text-gray-500 mt-0.5">
                      {voucher.pointItem?.name ||
                        `Diskon ${voucher.discount_type === 'PERCENTAGE' ? voucher.discount_value + '%' : formatIDR(voucher.discount_value)}`}
                    </p>
                  </div>
                  <div className="w-6 h-6 rounded-full bg-gray-100 group-hover:bg-yellow-100 flex items-center justify-center transition-colors">
                    <Check className="w-3.5 h-3.5 text-gray-400 group-hover:text-yellow-600 opacity-0 group-hover:opacity-100 transition-opacity" />
                  </div>
                </button>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export function SummaryRow({
  label,
  value,
  highlight,
  accent,
  muted,
}: {
  label: string;
  value: string;
  highlight?: boolean;
  accent?: boolean;
  muted?: boolean;
}) {
  return (
    <div className="flex items-center justify-between">
      <span
        className={cn(
          'text-xs tracking-wide',
          highlight ? 'font-bold text-gray-900' : 'font-medium text-gray-500'
        )}
      >
        {label}
      </span>
      <span
        className={cn(
          'text-sm',
          highlight
            ? 'font-black text-gray-900 text-lg'
            : accent
              ? 'font-bold text-rose-500'
              : muted
                ? 'font-medium text-gray-400 italic'
                : 'font-bold text-gray-900'
        )}
      >
        {value}
      </span>
    </div>
  );
}
