'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import toast from 'react-hot-toast';
import { X, Loader2, Eye, EyeOff } from 'lucide-react';
import { usersApi } from '@/lib/api';
import { User } from '@/types';

const schema = z.object({
  new_password: z.string().min(8).regex(
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/,
    'Upper, lower, digit, special char required'
  ),
  new_password_confirmation: z.string(),
}).refine((d) => d.new_password === d.new_password_confirmation, {
  path: ['new_password_confirmation'],
  message: 'Passwords must match',
});

interface Props {
  user: User;
  onClose: () => void;
  onReset: () => void;
}

export default function ResetPasswordModal({ user, onClose, onReset }: Props) {
  const [isLoading, setIsLoading] = useState(false);
  const [showPw, setShowPw] = useState(false);

  const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      await usersApi.resetPassword(user.id, data.new_password, data.new_password_confirmation);
      toast.success(`Password reset for @${user.username}`);
      onReset();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to reset password');
    } finally {
      setIsLoading(false);
    }
  });

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <div className="ts-card w-full max-w-sm">
        <div className="flex items-center justify-between px-6 py-4 border-b border-ts-border">
          <div>
            <h2 className="font-semibold text-ts-text">Reset Password</h2>
            <p className="text-xs text-ts-muted">@{user.username}</p>
          </div>
          <button onClick={onClose} className="ts-btn-ghost p-1.5"><X size={16} /></button>
        </div>

        <form onSubmit={onSubmit} className="px-6 py-5 space-y-4">
          <div>
            <label className="ts-label">New Password</label>
            <div className="relative">
              <input
                {...register('new_password')}
                type={showPw ? 'text' : 'password'}
                className="ts-input pr-10"
              />
              <button
                type="button"
                onClick={() => setShowPw(!showPw)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-ts-muted hover:text-ts-text"
              >
                {showPw ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
            {errors.new_password && (
              <p className="text-xs text-red-400 mt-1">{errors.new_password.message as string}</p>
            )}
          </div>

          <div>
            <label className="ts-label">Confirm Password</label>
            <input {...register('new_password_confirmation')} type="password" className="ts-input" />
            {errors.new_password_confirmation && (
              <p className="text-xs text-red-400 mt-1">{errors.new_password_confirmation.message as string}</p>
            )}
          </div>

          <p className="text-xs text-ts-muted">The user will be prompted to change this on next login.</p>

          <div className="flex gap-3">
            <button type="button" onClick={onClose} className="ts-btn-ghost flex-1">Cancel</button>
            <button type="submit" disabled={isLoading} className="ts-btn-primary flex-1 flex items-center justify-center gap-2">
              {isLoading && <Loader2 size={15} className="animate-spin" />}
              Reset
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
