'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 { usePermissions } from '@/lib/auth';

const schema = z.object({
  username: z.string().min(3).max(50).regex(/^[a-z0-9\-_]+$/, 'Lowercase, numbers, hyphens only'),
  name:     z.string().min(1).max(100),
  email:    z.string().email(),
  password: z.string().min(8).regex(
    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/,
    'Must include upper, lower, digit, special char'
  ),
  role: z.enum(['admin', 'operator']),
});

type FormData = z.infer<typeof schema>;

interface Props {
  onClose: () => void;
  onCreated: () => void;
}

export default function CreateUserModal({ onClose, onCreated }: Props) {
  const perms = usePermissions();
  const [isLoading, setIsLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: { role: 'operator' },
  });

  const onSubmit = handleSubmit(async (data) => {
    setIsLoading(true);
    try {
      await usersApi.create(data);
      toast.success(`User @${data.username} created`);
      onCreated();
    } catch (err: any) {
      const errs = err.response?.data?.errors;
      if (errs) {
        Object.values(errs).flat().forEach((m: any) => toast.error(m));
      } else {
        toast.error(err.response?.data?.message || 'Failed to create user');
      }
    } 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-md">
        <div className="flex items-center justify-between px-6 py-4 border-b border-ts-border">
          <h2 className="font-semibold text-ts-text">Add New User</h2>
          <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">Username</label>
            <input {...register('username')} className="ts-input" placeholder="john-doe" />
            {errors.username && <p className="text-xs text-red-400 mt-1">{errors.username.message}</p>}
            <p className="text-xs text-ts-muted mt-1">Lowercase, numbers, hyphens. Cannot be changed.</p>
          </div>

          <div>
            <label className="ts-label">Full Name</label>
            <input {...register('name')} className="ts-input" placeholder="John Doe" />
            {errors.name && <p className="text-xs text-red-400 mt-1">{errors.name.message}</p>}
          </div>

          <div>
            <label className="ts-label">Email</label>
            <input {...register('email')} type="email" className="ts-input" placeholder="john@example.com" />
            {errors.email && <p className="text-xs text-red-400 mt-1">{errors.email.message}</p>}
          </div>

          <div>
            <label className="ts-label">Temporary Password</label>
            <div className="relative">
              <input
                {...register('password')}
                type={showPassword ? 'text' : 'password'}
                className="ts-input pr-10"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-ts-muted hover:text-ts-text"
              >
                {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
            {errors.password && <p className="text-xs text-red-400 mt-1">{errors.password.message}</p>}
            <p className="text-xs text-ts-muted mt-1">User will be required to change on first login.</p>
          </div>

          <div>
            <label className="ts-label">Role</label>
            <select {...register('role')} className="ts-input">
              {perms.isMasterAdmin && <option value="admin">Admin</option>}
              <option value="operator">Operator</option>
            </select>
            {errors.role && <p className="text-xs text-red-400 mt-1">{errors.role.message}</p>}
          </div>

          <div className="flex gap-3 pt-2">
            <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" />}
              Create User
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
