'use client';

import React, { useState, useEffect } from 'react';
import { UserResponse, CreateUserDto, UpdateUserDto, Role } from '@goodgo/types';
import { User, Mail, Shield, Save, X } from 'lucide-react';
import { Button } from '../ui/button';
import { Card } from '../ui/card';
import { Input } from '../ui/input';
import { Select } from '../ui/select';
import { Switch } from '../ui/switch';
import { cn } from '@/shared/lib/utils';

/**
 * EN: Props for UserForm component
 * VI: Props cho component UserForm
 */
export interface UserFormProps {
  /** EN: User to edit (null for create mode) / VI: User để edit (null cho create mode) */
  user?: UserResponse | null;
  /** EN: Whether this is create mode / VI: Có phải create mode không */
  isCreate?: boolean;
  /** EN: Loading state / VI: Trạng thái loading */
  loading?: boolean;
  /** EN: Callback when form is submitted / VI: Callback khi form được submit */
  onSubmit: (data: CreateUserDto | UpdateUserDto) => Promise<void>;
  /** EN: Callback when form is cancelled / VI: Callback khi form bị cancel */
  onCancel?: () => void;
  /** EN: Additional CSS classes / VI: CSS classes bổ sung */
  className?: string;
}

/**
 * EN: User Form Component - Create and edit user forms
 * VI: Component User Form - Forms tạo và edit user
 *
 * Features:
 * - Create new user form
 * - Edit existing user form
 * - Form validation
 * - Role selection
 * - Password fields for creation
 * - Active status toggle
 */
export function UserForm({
  user,
  isCreate = false,
  loading = false,
  onSubmit,
  onCancel,
  className,
}: UserFormProps) {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    role: Role.USER,
    isActive: true,
  });

  const [errors, setErrors] = useState<Record<string, string>>({});

  // Initialize form data when user prop changes
  useEffect(() => {
    if (user) {
      setFormData({
        email: user.email,
        password: '',
        confirmPassword: '',
        role: user.role,
        isActive: user.isActive,
      });
    } else {
      setFormData({
        email: '',
        password: '',
        confirmPassword: '',
        role: Role.USER,
        isActive: true,
      });
    }
  }, [user]);

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear error for this field
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    // Email validation
    if (!formData.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }

    // Password validation (only for create mode)
    if (isCreate) {
      if (!formData.password) {
        newErrors.password = 'Password is required';
      } else if (formData.password.length < 8) {
        newErrors.password = 'Password must be at least 8 characters';
      }

      if (formData.password !== formData.confirmPassword) {
        newErrors.confirmPassword = 'Passwords do not match';
      }
    }

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

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

    if (!validateForm()) {
      return;
    }

    try {
      if (isCreate) {
        const createData: CreateUserDto = {
          email: formData.email,
          password: formData.password,
          role: formData.role,
        };
        await onSubmit(createData);
      } else {
        const updateData: UpdateUserDto = {
          email: formData.email,
          role: formData.role,
          isActive: formData.isActive,
        };
        await onSubmit(updateData);
      }
    } catch (error) {
      // Error handling is done in the parent component
    }
  };

  const roleOptions = [
    { value: Role.USER, label: 'User' },
    { value: Role.ADMIN, label: 'Admin' },
    { value: Role.SUPER_ADMIN, label: 'Super Admin' },
  ];

  return (
    <Card className={cn('p-6', className)}>
      <div className="flex items-center space-x-3 mb-6">
        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
          <User className="w-5 h-5 text-blue-600" />
        </div>
        <div>
          <h2 className="text-lg font-semibold text-gray-900">
            {isCreate ? 'Create New User' : 'Edit User'}
          </h2>
          <p className="text-sm text-gray-600">
            {isCreate ? 'Add a new user to the system' : 'Update user information and permissions'}
          </p>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Email Field */}
        <div>
          <label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-2">
            Email Address
          </label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <Input
              id="email"
              type="email"
              value={formData.email}
              onChange={(value) => handleInputChange('email', value)}
              className={cn(
                'pl-10',
                errors.email && 'border-red-300 focus:border-red-500 focus:ring-red-500'
              )}
              placeholder="user@example.com"
              isDisabled={loading}
            />
          </div>
          {errors.email && (
            <p className="mt-1 text-sm text-red-600">{errors.email}</p>
          )}
        </div>

        {/* Password Fields (Create Mode Only) */}
        {isCreate && (
          <>
            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
                Password
              </label>
              <Input
                id="password"
                type="password"
                value={formData.password}
                onChange={(value) => handleInputChange('password', value)}
                className={cn(
                  errors.password && 'border-red-300 focus:border-red-500 focus:ring-red-500'
                )}
                placeholder="Enter password"
                isDisabled={loading}
              />
              {errors.password && (
                <p className="mt-1 text-sm text-red-600">{errors.password}</p>
              )}
            </div>

            <div>
              <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-2">
                Confirm Password
              </label>
              <Input
                id="confirmPassword"
                type="password"
                value={formData.confirmPassword}
                onChange={(value) => handleInputChange('confirmPassword', value)}
                className={cn(
                  errors.confirmPassword && 'border-red-300 focus:border-red-500 focus:ring-red-500'
                )}
                placeholder="Confirm password"
                isDisabled={loading}
              />
              {errors.confirmPassword && (
                <p className="mt-1 text-sm text-red-600">{errors.confirmPassword}</p>
              )}
            </div>
          </>
        )}

        {/* Role Selection */}
        <div>
          <label htmlFor="role" className="block text-sm font-medium text-gray-700 mb-2">
            Role
          </label>
          <div className="relative">
            <Shield className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400 z-10" />
            <Select
              value={formData.role}
              onChange={(e) => handleInputChange('role', e.target.value as Role)}
              disabled={loading}
            >
              {roleOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </Select>
          </div>
        </div>

        {/* Active Status (Edit Mode Only) */}
        {!isCreate && (
          <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
            <div>
              <h4 className="text-sm font-medium text-gray-900">Account Status</h4>
              <p className="text-sm text-gray-600">
                {formData.isActive ? 'User can access the system' : 'User is deactivated'}
              </p>
            </div>
            <Switch
              checked={formData.isActive}
              onCheckedChange={(checked) => handleInputChange('isActive', checked)}
              disabled={loading}
            />
          </div>
        )}

        {/* Form Actions */}
        <div className="flex justify-end space-x-3 pt-6 border-t">
          {onCancel && (
            <Button
              type="button"
              variant="secondary"
              onClick={onCancel}
              isDisabled={loading}
            >
              <X className="w-4 h-4 mr-2" />
              Cancel
            </Button>
          )}
          <Button
            type="submit"
            isDisabled={loading}
            className="min-w-[120px]"
          >
            {loading ? (
              <>
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
                {isCreate ? 'Creating...' : 'Saving...'}
              </>
            ) : (
              <>
                <Save className="w-4 h-4 mr-2" />
                {isCreate ? 'Create User' : 'Save Changes'}
              </>
            )}
          </Button>
        </div>
      </form>
    </Card>
  );
}