import { useState, useEffect } 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 EditUserModal = ({ isOpen, user, onClose, onSubmit }) => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    middleName: '',
    country: '',
    website: '',
    dob: '',
    gender: '',
    curntFirstName: '',
    curntMiddleName: '',
    curntLastName: '',
    status: 1,
    activeStatus: 1,
    role: 'user',
    promotionalEmails: 0,
    licenseCode: '',
    licenseCodeStatus: 0,
    licenseDate: '',
    subscriptionType: '',
    notes: ''
  })

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

  useEffect(() => {
    if (user) {
      setFormData({
        firstName: user.first_name || '',
        lastName: user.last_name || '',
        email: user.email || '',
        phone: user.phone || '',
        middleName: user.middle_name || '',
        country: user.country || '',
        website: user.website || '',
        dob: user.dob ? user.dob.split('T')[0] : '',
        gender: user.gender || '',
        curntFirstName: user.curnt_first_name || '',
        curntMiddleName: user.curnt_middle_name || '',
        curntLastName: user.curnt_last_name || '',
        status: user.status !== undefined ? user.status : 1,
        activeStatus: user.active_status || 1,
        role: user.role === 1 ? 'admin' : 'user',
        promotionalEmails: user.promotional_emails || 0,
        licenseCode: user.license_code || '',
        licenseCodeStatus: user.license_code_status || 0,
        licenseDate: user.license_date ? user.license_date.split('T')[0] : '',
        subscriptionType: user.subscription_type ?? '',
        notes: user.notes || ''
      })
    }
  }, [user, isOpen])

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

  const handleCopyLicenseCode = async () => {
    if (!formData.licenseCode) return
    try {
      await navigator.clipboard.writeText(formData.licenseCode)
      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,
        licenseCode: licenseCode,
        licenseCodeStatus: 1,
        licenseDate: todayDate
      }))
      setIsLicenseConfirmOpen(false)
    } finally {
      setIsGeneratingLicense(false)
    }
  }

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

    if (formData.licenseCode || formData.licenseCodeStatus || formData.licenseDate || formData.subscriptionType) {
      if (!formData.licenseCode) newErrors.licenseCode = 'Required for subscription'
      if (!formData.licenseDate) newErrors.licenseDate = 'Required for subscription'
      if (!formData.subscriptionType) newErrors.subscriptionType = 'Required for subscription'
    }

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

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

    setIsLoading(true)
    try {
      const payload = {
        first_name: formData.firstName,
        last_name: formData.lastName,
        email: formData.email,
        phone: formData.phone,
        middle_name: formData.middleName,
        country: formData.country,
        website: formData.website,
        dob: formData.dob,
        gender: formData.gender,
        curnt_first_name: formData.curntFirstName,
        curnt_middle_name: formData.curntMiddleName,
        curnt_last_name: formData.curntLastName,
        status: formData.status,
        active_status: formData.activeStatus,
        role: formData.role === 'admin' ? 1 : 0,
        promotional_emails: formData.promotionalEmails,
        license_code: formData.licenseCode,
        license_code_status: formData.licenseCodeStatus,
        license_date: formData.licenseDate,
        subscription_type: formData.subscriptionType === '' ? null : parseInt(formData.subscriptionType, 10),
        notes: formData.notes
      }
      await onSubmit(payload)
      setErrors({})
    } finally {
      setIsLoading(false)
    }
  }

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

        {/* ── SECTION: ACCOUNT IDENTITY ── */}
        <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 Information</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Input label="First Name" value={formData.firstName} onChange={(e) => setFormData({ ...formData, firstName: e.target.value })} error={errors.firstName} required />
            <Input label="Middle Name" value={formData.middleName} onChange={(e) => setFormData({ ...formData, middleName: e.target.value })} />
            <Input label="Last Name" value={formData.lastName} onChange={(e) => setFormData({ ...formData, lastName: e.target.value })} />
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Input label="Email Address" value={formData.email} onChange={(e) => setFormData({ ...formData, email: e.target.value })} error={errors.email} required placeholder="email@example.com" />
            <Input label="Contact Phone" value={formData.phone} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} placeholder="+1 (555) 000-0000" />
            <Input type="date" label="Date of Birth" value={formData.dob} onChange={(e) => setFormData({ ...formData, dob: e.target.value })} />
            <Input label="Gender Identity" value={formData.gender} onChange={(e) => setFormData({ ...formData, gender: e.target.value })} placeholder="Male/Female/Other" />
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Input label="Residence Country" value={formData.country} onChange={(e) => setFormData({ ...formData, country: e.target.value })} />
            <Input label="Personal Website" value={formData.website} onChange={(e) => setFormData({ ...formData, website: e.target.value })} />
          </div>
        </div>

        {/* ── SECTION: 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 Identity</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <Input label="Legal First Name" value={formData.curntFirstName} onChange={(e) => setFormData({ ...formData, curntFirstName: e.target.value })} />
            <Input label="Legal Middle Name" value={formData.curntMiddleName} onChange={(e) => setFormData({ ...formData, curntMiddleName: e.target.value })} />
            <Input label="Legal Last Name" value={formData.curntLastName} onChange={(e) => setFormData({ ...formData, curntLastName: e.target.value })} />
          </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 Management</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" value={formData.licenseCode} onChange={(e) => setFormData({ ...formData, licenseCode: e.target.value })} error={errors.licenseCode} 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" value={formData.licenseDate} onChange={(e) => setFormData({ ...formData, licenseDate: e.target.value })} error={errors.licenseDate} />

            <div>
              <label className="block text-lg font-black mb-2 text-[#111827]">License Status</label>
              <select
                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.licenseCodeStatus}
                onChange={(e) => setFormData({ ...formData, licenseCodeStatus: 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
              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.subscriptionType ? 'border-[#E74C3C]' : 'border-gray-200'}`}
              value={formData.subscriptionType}
              onChange={(e) => setFormData({ ...formData, subscriptionType: e.target.value })}
            >
              <option value="">Select subscription type</option>
              {SUBSCRIPTION_TYPE_OPTIONS.map(option => (
                <option key={option.value} value={option.value}>{option.label}</option>
              ))}
            </select>
            {errors.subscriptionType && (
              <p className="text-[#E74C3C] text-sm mt-1 font-medium">{errors.subscriptionType}</p>
            )}
          </div>
        </div>

        {/* ── SECTION: ADMINISTRATION ── */}
        <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 & Internal</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 Status</label>
              <select
                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({ ...formData, status: 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]">Newsletter Subscription</label>
              <select
                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.promotionalEmails}
                onChange={(e) => setFormData({ ...formData, promotionalEmails: parseInt(e.target.value) })}
              >
                <option value={1}>✅ SUBSCRIBED</option>
                <option value={0}>❌ OPTED OUT</option>
              </select>
            </div>
          </div>

          <div className="space-y-2">
            <label className="block text-lg font-black text-[#111827]">Internal Administrative Notes</label>
            <textarea
              name="notes"
              value={formData.notes || ''}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
              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 min-h-[140px]"
              placeholder="Record any internal context or administrative history here..."
            />
          </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">
            Save Profile Updates
          </Button>
        </div>
      </div>

      <ConfirmDialog
        isOpen={isLicenseConfirmOpen}
        onClose={() => setIsLicenseConfirmOpen(false)}
        onConfirm={handleConfirmGenerateLicense}
        title="Regenerate License Code"
        message="Generate a new license code? This will replace the current code, set status to active, and update the date."
        confirmText="Confirm Change"
        cancelText="Keep Current"
        isLoading={isGeneratingLicense}
      />
    </Modal>
  )
}

export default EditUserModal
