'use client';

import { useState } from 'react';
import { X, Loader2 } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
import { toast } from 'react-hot-toast';

interface CreateUserModalProps {
  show: boolean;
  onClose: () => void;
  onUserCreated: () => void;
}

export default function CreateUserModal({ show, onClose, onUserCreated }: CreateUserModalProps) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [errors, setErrors] = useState<{ username?: string; password?: string }>({});
  const [loading, setLoading] = useState(false);

  if (!show) return null;

  const validateForm = () => {
    const newErrors: typeof errors = {};

    if (!username.trim()) {
      newErrors.username = 'Username is required';
    }

    if (!password.trim()) {
      newErrors.password = 'Password is required';
    } else if (password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;

    setLoading(true);
    try {
      await inventoryApi.createUser({
        username: username.trim(),
        password,
        role: 'user'
      });

      toast.success('User created successfully');
      setUsername('');
      setPassword('');
      setErrors({});
      onUserCreated();
      onClose();
    } catch (error: any) {
      const errorMsg = error?.response?.data?.detail || 'Failed to create user';
      if (errorMsg.includes('already exists')) {
        setErrors({ username: 'Username already exists' });
      } else {
        toast.error(errorMsg);
      }
    } finally {
      setLoading(false);
    }
  };

  const isFormValid = username.trim() && password.length >= 6 && !Object.keys(errors).length;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-surface border border-slate-800 rounded-lg shadow-xl max-w-sm w-full mx-4">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <h2 className="text-lg font-black text-white">Create User</h2>
          <button
            onClick={onClose}
            className="p-1 text-muted hover:text-slate-300 rounded focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none"
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {/* Username Field */}
          <div>
            <label htmlFor="username" className="block text-sm font-semibold text-slate-300 mb-2">
              Username
            </label>
            <input
              id="username"
              type="text"
              value={username}
              onChange={(e) => {
                setUsername(e.target.value);
                if (errors.username) setErrors({ ...errors, username: undefined });
              }}
              placeholder="Enter username"
              className={`w-full px-3 py-2.5 bg-slate-800 border rounded text-white placeholder-slate-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
                errors.username ? 'border-red-500' : 'border-slate-700'
              }`}
              disabled={loading}
            />
            {errors.username && (
              <p className="mt-1.5 text-sm text-red-500">{errors.username}</p>
            )}
          </div>

          {/* Password Field */}
          <div>
            <label htmlFor="password" className="block text-sm font-semibold text-slate-300 mb-2">
              Password
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => {
                setPassword(e.target.value);
                if (errors.password) setErrors({ ...errors, password: undefined });
              }}
              placeholder="Enter password"
              className={`w-full px-3 py-2.5 bg-slate-800 border rounded text-white placeholder-slate-500 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
                errors.password ? 'border-red-500' : 'border-slate-700'
              }`}
              disabled={loading}
            />
            {errors.password && (
              <p className="mt-1.5 text-sm text-red-500">{errors.password}</p>
            )}
          </div>

          {/* Buttons */}
          <div className="flex gap-2 pt-4">
            <button
              type="button"
              onClick={onClose}
              disabled={loading}
              className="flex-1 px-4 py-2.5 text-slate-300 bg-slate-800 border border-slate-700 rounded font-semibold hover:bg-slate-700 transition-colors disabled:opacity-50 focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={!isFormValid || loading}
              className="flex-1 px-4 py-2.5 bg-primary text-primary-foreground rounded font-semibold hover:bg-blue-600 transition-colors disabled:opacity-50 flex items-center justify-center gap-2 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-slate-900 focus-visible:ring-primary focus-visible:outline-none"
            >
              {loading ? (
                <>
                  <Loader2 size={16} className="animate-spin" />
                  Creating...
                </>
              ) : (
                'Create'
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
