import { useState } from 'react'
import Modal from '../components/common/Modal'
import Input from '../components/common/Input'
import Button from '../components/common/Button'
import ConfirmDialog from '../components/common/ConfirmDialog'
import { generateLicenseCode, getTodayDate } from '../utils/helpers'
import { showToast } from '../utils/toast'
import { SUBSCRIPTION_TYPE_OPTIONS } from '../utils/subscriptionTypes'

const AddUserModal = ({ isOpen, onClose, onSubmit }) => {
  const initialFormData = {
    first_name: '',
    middle_name: '',
    last_name: '',
    email: '',
    password: '',
    phone: '',
    country: '',
    website: '',
    dob: '',
    gender: '',
    curnt_first_name: '',
    curnt_middle_name: '',
    curnt_last_name: '',
    status: 1, // Default to Active (1)
    promotional_emails: 0,
    license_code: '',
    license_code_status: 0,
    license_date: '',
    subscription_type: '',
    notes: ''
  }

  const [formData, setFormData] = useState(initialFormData)
  const [errors, setErrors] = useState({})
  const [isLoading, setIsLoading] = useState(false)
  const [isLicenseConfirmOpen, setIsLicenseConfirmOpen] = useState(false)
  const [isGeneratingLicense, setIsGeneratingLicense] = useState(false)

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleGenerateLicense = () => {
    setIsLicenseConfirmOpen(true)
  }

  const handleCopyLicenseCode = async () => {
    if (!formData.license_code) return
    try {
      await navigator.clipboard.writeText(formData.license_code)
      showToast.success('License code copied')
    } catch (error) {
      showToast.error('Failed to copy license code')
    }
  }

  const handleConfirmGenerateLicense = async () => {
    setIsGeneratingLicense(true)
    try {
      const licenseCode = generateLicenseCode()
      const todayDate = getTodayDate()

      setFormData(prev => ({
        ...prev,
        license_code: licenseCode,
        license_code_status: 1,
        license_date: todayDate
      }))
      setIsLicenseConfirmOpen(false)
    } finally {
      setIsGeneratingLicense(false)
    }
  }

  const validateForm = () => {
    const newErrors = {}
    if (!formData.first_name) newErrors.first_name = 'First Name is required'
    if (!formData.email) newErrors.email = 'Email is required'
    if (!formData.password) newErrors.password = 'Password is required'

    const hasSubDetails = formData.license_code || formData.license_date || formData.license_code_status === 1 || formData.subscription_type;

    if (hasSubDetails) {
      if (!formData.license_code) newErrors.license_code = 'License Code is required';
      if (!formData.license_date) newErrors.license_date = 'Expiration Date is required';
      if (!formData.subscription_type) newErrors.subscription_type = 'Subscription Type is required';
    }

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

  const handleSubmit = async () => {
    if (!validateForm()) return

    setIsLoading(true)
    try {
      await onSubmit({
        ...formData,
        subscription_type: formData.subscription_type === '' ? null : parseInt(formData.subscription_type, 10)
      })
      setFormData(initialFormData)
      setErrors({})
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Add New User"
      size="3xl"
    >
      <div className="max-h-[75vh] overflow-y-auto px-2 space-y-8 custom-scrollbar">

        {/* ── SECTION: PERSONAL PROFILE ── */}
        <div className="space-y-5">
          <div className="flex items-center gap-3 pb-3 border-b-4 border-[#409CA4]/10">
            <div className="w-10 h-10 bg-[#409CA4] rounded-lg flex items-center justify-center text-white shadow-lg">
              <span className="text-xl">👤</span>
            </div>
            <h3 className="text-xl font-black text-[#111827]">Account Identification</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Input label="First Name" name="first_name" value={formData.first_name} onChange={handleChange} error={errors.first_name} required />
            <Input label="Middle Name" name="middle_name" value={formData.middle_name} onChange={handleChange} />
            <Input label="Last Name" name="last_name" value={formData.last_name} onChange={handleChange} />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Input label="Email Address" type="email" name="email" value={formData.email} onChange={handleChange} error={errors.email} required placeholder="email@example.com" />
            <Input label="Secure Password" type="password" name="password" value={formData.password} onChange={handleChange} error={errors.password} required placeholder="••••••••" />
            <Input label="Primary Phone" name="phone" value={formData.phone} onChange={handleChange} placeholder="+1 (555) 000-0000" />
            <Input type="date" label="Date of Birth" name="dob" value={formData.dob} onChange={handleChange} />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Input label="Gender" name="gender" value={formData.gender} onChange={handleChange} placeholder="Male/Female/Other" />
            <Input label="Origin Country" name="country" value={formData.country} onChange={handleChange} />
            <Input label="Portfolio / Website" name="website" value={formData.website} onChange={handleChange} />
          </div>
        </div>

        {/* ── SECTION: FULL LEGAL NAME ── */}
        <div className="space-y-5">
          <div className="flex items-center gap-3 pb-3 border-b-4 border-[#e8713a]/10">
            <div className="w-10 h-10 bg-[#e8713a] rounded-lg flex items-center justify-center text-white shadow-lg">
              <span className="text-xl">📝</span>
            </div>
            <h3 className="text-xl font-black text-[#111827]">Current Legal Name Details</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Input label="Legal First Name" name="curnt_first_name" value={formData.curnt_first_name} onChange={handleChange} />
            <Input label="Legal Middle Name" name="curnt_middle_name" value={formData.curnt_middle_name} onChange={handleChange} />
            <Input label="Legal Last Name" name="curnt_last_name" value={formData.curnt_last_name} onChange={handleChange} />
          </div>
        </div>

        {/* ── SECTION: SUBSCRIPTION ── */}
        <div className="space-y-5 bg-gray-50 p-6 rounded-3xl border-2 border-dashed border-[#409CA4]/30">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-[#409CA4] rounded-lg flex items-center justify-center text-white shadow-lg">
              <span className="text-xl">💳</span>
            </div>
            <h3 className="text-xl font-black text-[#111827]">License & Subscription</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 items-end">
            <div className="space-y-3">
              <Input label="License Code" name="license_code" value={formData.license_code} onChange={handleChange} error={errors.license_code} placeholder="ENTER-CODE-HERE" />
              <div className="grid grid-cols-2 gap-2">
                <Button onClick={handleGenerateLicense} variant="secondary" size="md" className="w-full">
                  🔐 Generate
                </Button>
                <Button onClick={handleCopyLicenseCode} variant="outline" size="md" className="w-full">
                  📋 Copy
                </Button>
              </div>
            </div>
            <Input type="date" label="Expiration Date" name="license_date" value={formData.license_date} onChange={handleChange} error={errors.license_date} />
            <div>
              <label className="block text-lg font-black mb-2 text-[#111827]">License Status</label>
              <select
                name="license_code_status"
                className="w-full px-4 py-4 rounded-xl border-2 border-gray-200 bg-white focus:border-[#409CA4] outline-none font-black text-[#111827] cursor-pointer"
                value={formData.license_code_status}
                onChange={(e) => setFormData(prev => ({ ...prev, license_code_status: parseInt(e.target.value) }))}
              >
                <option value={0}>❌ INACTIVE / FREE</option>
                <option value={1}>✅ ACTIVE / PAID</option>
              </select>
            </div>
          </div>
          <div>
            <label className="block text-lg font-black mb-2 text-[#111827]">Subscription Type</label>
            <select
              name="subscription_type"
              className={`w-full px-4 py-4 rounded-xl border-2 bg-white focus:border-[#409CA4] outline-none font-black text-[#111827] cursor-pointer ${errors.subscription_type ? 'border-[#E74C3C]' : 'border-gray-200'}`}
              value={formData.subscription_type}
              onChange={handleChange}
            >
              <option value="">Select subscription type</option>
              {SUBSCRIPTION_TYPE_OPTIONS.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            {errors.subscription_type && (
              <p className="text-[#E74C3C] text-sm mt-1 font-medium">{errors.subscription_type}</p>
            )}
          </div>
        </div>

        {/* ── SECTION: ADMIN BRAIN ── */}
        <div className="space-y-5">
          <div className="flex items-center gap-3 pb-3 border-b-4 border-[#5cb85c]/10">
            <div className="w-10 h-10 bg-[#5cb85c] rounded-lg flex items-center justify-center text-white shadow-lg">
              <span className="text-xl">⚙️</span>
            </div>
            <h3 className="text-xl font-black text-[#111827]">Administrative Controls</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-lg font-black mb-2 text-[#111827]">Account Visibility</label>
              <select
                name="status"
                className="w-full px-4 py-4 rounded-xl border-2 border-gray-200 bg-white focus:border-[#409CA4] outline-none font-black text-[#111827] cursor-pointer"
                value={formData.status}
                onChange={(e) => setFormData(prev => ({ ...prev, status: parseInt(e.target.value) }))}
              >
                <option value={1}>✅ SYSTEM ACTIVE</option>
                <option value={0}>⊗ SYSTEM INACTIVE</option>
              </select>
            </div>
            <div>
              <label className="block text-lg font-black mb-2 text-[#111827]">Email Communications</label>
              <select
                name="promotional_emails"
                className="w-full px-4 py-4 rounded-xl border-2 border-gray-200 bg-white focus:border-[#409CA4] outline-none font-black text-[#111827] cursor-pointer"
                value={formData.promotional_emails}
                onChange={(e) => setFormData(prev => ({ ...prev, promotional_emails: parseInt(e.target.value) }))}
              >
                <option value={0}>❌ OPTED OUT</option>
                <option value={1}>✅ OPTED IN</option>
              </select>
            </div>
          </div>

          <div className="space-y-2">
            <label className="block text-lg font-black text-[#111827]">Internal Admin Notes</label>
            <textarea
              name="notes"
              rows={4}
              value={formData.notes || ''}
              onChange={handleChange}
              placeholder="Add internal notes about this user account..."
              className="w-full px-5 py-4 rounded-2xl border-2 border-gray-200 bg-white focus:border-[#409CA4] outline-none font-bold text-[#111827] placeholder:text-gray-300 transition-colors"
            />
          </div>
        </div>

        <div className="flex gap-4 justify-end pt-6 border-t-4 border-gray-100 pb-1">
          <Button onClick={onClose} variant="outline" size="lg" disabled={isLoading} className="px-8 border-2">Cancel</Button>
          <Button onClick={handleSubmit} isLoading={isLoading} size="lg" className="px-10">
            Create User Record
          </Button>
        </div>
      </div>

      <ConfirmDialog
        isOpen={isLicenseConfirmOpen}
        onClose={() => setIsLicenseConfirmOpen(false)}
        onConfirm={handleConfirmGenerateLicense}
        title="Generate License Code"
        message="Generate a new 32-character license code? This will set the license status to active and use today's date."
        confirmText="Generate"
        cancelText="Cancel"
        isLoading={isGeneratingLicense}
      />
    </Modal>
  )
}

export default AddUserModal
