import { useState } from 'react'
import { User, Mail, Phone, Building, Crown, Key, UserCheck, X } from 'lucide-react'
import Modal from './Modal'
import toast from 'react-hot-toast'

const UserModal = ({ 
  isOpen, 
  onClose, 
  user = null, 
  onSave, 
  mode = 'create' // 'create' or 'edit'
}) => {
  const [formData, setFormData] = useState({
    first_name: user?.first_name || '',
    last_name: user?.last_name || '',
    email: user?.email || '',
    phone_number: user?.phone_number || '',
    company_name: user?.company_name || '',
    subscription_type: user?.subscription_type || 'free',
    is_api_enabled: user?.is_api_enabled || false,
    is_verified: user?.is_verified || false,
  })

  const [isLoading, setIsLoading] = useState(false)

  const handleSubmit = async (e) => {
    e.preventDefault()
    setIsLoading(true)

    try {
      await onSave(formData)
      toast.success(`User ${mode === 'create' ? 'created' : 'updated'} successfully`)
      onClose()
    } catch (error) {
      toast.error(`Failed to ${mode === 'create' ? 'create' : 'update'} user`)
    } finally {
      setIsLoading(false)
    }
  }

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }))
  }

  const subscriptionTypes = [
    { value: 'free', label: 'Free', icon: User, color: 'gray' },
    { value: 'paid', label: 'Paid', icon: Crown, color: 'blue' },
    { value: 'premium', label: 'Premium', icon: Crown, color: 'purple' },
  ]

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={mode === 'create' ? 'Add New User' : 'Edit User'}
      size="lg"
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Basic Information */}
        <div>
          <h4 className="text-md font-medium text-gray-900 dark:text-white mb-4">
            Basic Information
          </h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="label">First Name</label>
              <input
                type="text"
                name="first_name"
                value={formData.first_name}
                onChange={handleChange}
                className="input"
                required
              />
            </div>
            <div>
              <label className="label">Last Name</label>
              <input
                type="text"
                name="last_name"
                value={formData.last_name}
                onChange={handleChange}
                className="input"
                required
              />
            </div>
          </div>
        </div>

        {/* Contact Information */}
        <div>
          <h4 className="text-md font-medium text-gray-900 dark:text-white mb-4">
            Contact Information
          </h4>
          <div className="space-y-4">
            <div>
              <label className="label">Email Address</label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className="input pl-10"
                  required
                />
              </div>
            </div>
            <div>
              <label className="label">Phone Number</label>
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="tel"
                  name="phone_number"
                  value={formData.phone_number}
                  onChange={handleChange}
                  className="input pl-10"
                />
              </div>
            </div>
            <div>
              <label className="label">Company Name</label>
              <div className="relative">
                <Building className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  name="company_name"
                  value={formData.company_name}
                  onChange={handleChange}
                  className="input pl-10"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Subscription & Access */}
        <div>
          <h4 className="text-md font-medium text-gray-900 dark:text-white mb-4">
            Subscription & Access
          </h4>
          <div className="space-y-4">
            <div>
              <label className="label">Subscription Type</label>
              <div className="grid grid-cols-3 gap-3">
                {subscriptionTypes.map((type) => {
                  const Icon = type.icon
                  return (
                    <label
                      key={type.value}
                      className={`relative flex items-center p-3 border rounded-lg cursor-pointer transition-colors ${
                        formData.subscription_type === type.value
                          ? 'border-primary-500 bg-primary-50 dark:bg-primary-900/20'
                          : 'border-gray-300 dark:border-gray-600 hover:border-gray-400'
                      }`}
                    >
                      <input
                        type="radio"
                        name="subscription_type"
                        value={type.value}
                        checked={formData.subscription_type === type.value}
                        onChange={handleChange}
                        className="sr-only"
                      />
                      <Icon className={`h-5 w-5 mr-2 text-${type.color}-600`} />
                      <span className="text-sm font-medium">{type.label}</span>
                    </label>
                  )
                })}
              </div>
            </div>

            <div className="flex items-center space-x-6">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  name="is_api_enabled"
                  checked={formData.is_api_enabled}
                  onChange={handleChange}
                  className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                />
                <span className="ml-2 text-sm text-gray-900 dark:text-white">
                  <Key className="inline h-4 w-4 mr-1" />
                  API Access Enabled
                </span>
              </label>

              <label className="flex items-center">
                <input
                  type="checkbox"
                  name="is_verified"
                  checked={formData.is_verified}
                  onChange={handleChange}
                  className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                />
                <span className="ml-2 text-sm text-gray-900 dark:text-white">
                  <UserCheck className="inline h-4 w-4 mr-1" />
                  Email Verified
                </span>
              </label>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center justify-end space-x-3 pt-4 border-t border-gray-200 dark:border-gray-700">
          <button
            type="button"
            onClick={onClose}
            className="btn btn-secondary"
            disabled={isLoading}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="btn btn-primary"
            disabled={isLoading}
          >
            {isLoading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                {mode === 'create' ? 'Creating...' : 'Updating...'}
              </>
            ) : (
              <>
                <User className="h-4 w-4 mr-2" />
                {mode === 'create' ? 'Create User' : 'Update User'}
              </>
            )}
          </button>
        </div>
      </form>
    </Modal>
  )
}

export default UserModal
