import { useState, useEffect } from 'react'
import { Plus, Shield, Edit2, Trash2, UserCheck } from 'lucide-react'
import { api } from '../utils/api'
import Modal from '../components/Modal'
import { useAuth } from '../contexts/AuthContext'
import { useLanguage } from '../i18n/LanguageContext'
import { useToast } from '../components/ToastContainer'
import { SkeletonTable } from '../components/SkeletonLoader'

const ROLES = [
  { value: 'superadmin', label: 'Superadmin', color: 'bg-purple-100 text-purple-700', icon: '👑' },
  { value: 'manager', label: 'Manager', color: 'bg-blue-100 text-blue-700', icon: '📊' },
  { value: 'contributor', label: 'Contributor', color: 'bg-green-100 text-green-700', icon: '✏️' },
]

const EMPTY_FORM = {
  name: '', email: '', password: '', role: 'contributor', avatar: '',
}

function RoleBadge({ role }) {
  const roleInfo = ROLES.find(r => r.value === role) || ROLES[2]
  return (
    <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${roleInfo.color}`}>
      <span>{roleInfo.icon}</span>
      {roleInfo.label}
    </span>
  )
}

export default function Users() {
  const { user: currentUser } = useAuth()
  const { t } = useLanguage()
  const toast = useToast()
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)
  const [showModal, setShowModal] = useState(false)
  const [editingUser, setEditingUser] = useState(null)
  const [form, setForm] = useState(EMPTY_FORM)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [userToDelete, setUserToDelete] = useState(null)
  const [confirmPassword, setConfirmPassword] = useState('')
  const [passwordError, setPasswordError] = useState('')

  useEffect(() => { loadUsers() }, [])

  const loadUsers = async () => {
    try {
      const res = await api.get('/users')
      setUsers(res)
    } catch (err) {
      console.error('Failed to load users:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    setPasswordError('')
    if (form.password && form.password !== confirmPassword) {
      setPasswordError(t('users.passwordMismatch'))
      return
    }
    try {
      const data = {
        name: form.name,
        email: form.email,
        role: form.role,
        avatar: form.avatar || null,
      }
      if (form.password) data.password = form.password

      if (editingUser) {
        await api.patch(`/users/${editingUser.id}`, data)
      } else {
        if (!form.password) {
          toast.error(t('users.passwordRequired'))
          return
        }
        data.password = form.password
        await api.post('/users', data)
      }
      setShowModal(false)
      setEditingUser(null)
      setForm(EMPTY_FORM)
      loadUsers()
    } catch (err) {
      console.error('Save failed:', err)
      toast.error(t('users.saveFailed') + ': ' + err.message)
    }
  }

  const openEdit = (user) => {
    setEditingUser(user)
    setForm({
      name: user.name || '',
      email: user.email || '',
      password: '',
      role: user.role || 'contributor',
      avatar: user.avatar || '',
    })
    setConfirmPassword('')
    setPasswordError('')
    setShowModal(true)
  }

  const openNew = () => {
    setEditingUser(null)
    setForm(EMPTY_FORM)
    setConfirmPassword('')
    setPasswordError('')
    setShowModal(true)
  }

  const confirmDelete = async () => {
    if (!userToDelete) return
    try {
      await api.delete(`/users/${userToDelete.id}`)
      loadUsers()
      setUserToDelete(null)
    } catch (err) {
      console.error('Delete failed:', err)
      toast.error(t('users.deleteFailed'))
    }
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-12 bg-surface-tertiary rounded-xl animate-pulse"></div>
        <SkeletonTable rows={5} cols={5} />
      </div>
    )
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
            <Shield className="w-7 h-7 text-purple-600" />
            {t('users.title')}
          </h1>
          <p className="text-sm text-text-tertiary mt-1">{users.length} {users.length !== 1 ? t('users.usersPlural') : t('users.userSingular')}</p>
        </div>
        <button
          onClick={openNew}
          className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light shadow-sm"
        >
          <Plus className="w-4 h-4" />
          {t('users.addUser')}
        </button>
      </div>

      {/* Users List */}
      <div className="bg-white rounded-xl border border-border overflow-hidden">
        <table className="w-full">
          <thead>
            <tr className="border-b border-border bg-surface-secondary">
              <th className="text-left px-5 py-3 text-xs font-semibold text-text-tertiary uppercase tracking-wider">{t('users.userSingular')}</th>
              <th className="text-left px-5 py-3 text-xs font-semibold text-text-tertiary uppercase tracking-wider">{t('users.email')}</th>
              <th className="text-left px-5 py-3 text-xs font-semibold text-text-tertiary uppercase tracking-wider">{t('users.role')}</th>
              <th className="text-left px-5 py-3 text-xs font-semibold text-text-tertiary uppercase tracking-wider">{t('users.created')}</th>
              <th className="text-right px-5 py-3 text-xs font-semibold text-text-tertiary uppercase tracking-wider w-24">{t('users.actions')}</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border-light">
            {users.length === 0 ? (
              <tr>
                <td colSpan={5} className="py-12 text-center text-sm text-text-tertiary">
                  {t('users.noUsers')}
                </td>
              </tr>
            ) : (
              users.map(user => {
                const isCurrentUser = currentUser?.id === user.id
                const roleInfo = ROLES.find(r => r.value === user.role) || ROLES[2]
                return (
                  <tr key={user.id} className="hover:bg-surface-secondary group">
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-3">
                        <div className={`w-10 h-10 rounded-full bg-gradient-to-br ${user.role === 'superadmin' ? 'from-purple-500 to-pink-500' : 'from-blue-500 to-indigo-500'} flex items-center justify-center text-white font-bold text-sm`}>
                          {user.name?.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()}
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <p className="text-sm font-medium text-text-primary">{user.name}</p>
                            {isCurrentUser && (
                              <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-700 font-medium">
                                {t('users.you')}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-4 text-sm text-text-secondary">{user.email}</td>
                    <td className="px-5 py-4">
                      <RoleBadge role={user.role} />
                    </td>
                    <td className="px-5 py-4 text-sm text-text-tertiary">
                      {user.createdAt ? new Date(user.createdAt).toLocaleDateString() : '—'}
                    </td>
                    <td className="px-5 py-4">
                      <div className="flex items-center justify-end gap-1">
                        <button
                          onClick={() => openEdit(user)}
                          className="p-1.5 hover:bg-surface-tertiary rounded-lg text-text-tertiary hover:text-text-primary"
                          title={t('users.editUser')}
                        >
                          <Edit2 className="w-4 h-4" />
                        </button>
                        {!isCurrentUser && (
                          <button
                            onClick={() => { setUserToDelete(user); setShowDeleteConfirm(true) }}
                            className="p-1.5 hover:bg-red-50 rounded-lg text-text-tertiary hover:text-red-500"
                            title={t('users.deleteUser')}
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                )
              })
            )}
          </tbody>
        </table>
      </div>

      {/* Add/Edit User Modal */}
      <Modal
        isOpen={showModal}
        onClose={() => { setShowModal(false); setEditingUser(null) }}
        title={editingUser ? t('users.editUser') : t('users.addNewUser')}
        size="md"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('users.name')} *</label>
            <input
              type="text"
              value={form.name}
              onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder={t('users.fullNamePlaceholder')}
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('users.email')} *</label>
            <input
              type="email"
              value={form.email}
              onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder="user@company.com"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">
              {t('users.password')} {editingUser && `(${t('users.leaveBlankToKeep')})`}
            </label>
            <input
              type="password"
              value={form.password}
              onChange={e => { setForm(f => ({ ...f, password: e.target.value })); setPasswordError('') }}
              className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
              placeholder="••••••••"
              required={!editingUser}
            />
          </div>

          {form.password && (
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1">{t('users.confirmPassword')}</label>
              <input
                type="password"
                value={confirmPassword}
                onChange={e => { setConfirmPassword(e.target.value); setPasswordError('') }}
                className="w-full px-3 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary"
                placeholder="••••••••"
              />
              {passwordError && (
                <p className="text-xs text-red-500 mt-1">{passwordError}</p>
              )}
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-text-primary mb-1">{t('users.role')} *</label>
            <div className="grid grid-cols-3 gap-2">
              {ROLES.map(r => (
                <button
                  key={r.value}
                  type="button"
                  onClick={() => setForm(f => ({ ...f, role: r.value }))}
                  className={`p-3 rounded-lg border-2 text-center transition-all ${
                    form.role === r.value
                      ? 'border-brand-primary bg-brand-primary/5'
                      : 'border-border hover:border-brand-primary/30'
                  }`}
                >
                  <div className="text-2xl mb-1">{r.icon}</div>
                  <div className="text-xs font-medium text-text-primary">{r.label}</div>
                </button>
              ))}
            </div>
          </div>

          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border">
            <button
              onClick={() => { setShowModal(false); setEditingUser(null) }}
              className="px-4 py-2 text-sm font-medium text-text-secondary hover:bg-surface-tertiary rounded-lg"
            >
              {t('common.cancel')}
            </button>
            <button
              onClick={handleSave}
              disabled={!form.name || !form.email || (!editingUser && !form.password)}
              className="px-5 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
            >
              {editingUser ? t('users.saveChanges') : t('users.addUser')}
            </button>
          </div>
        </div>
      </Modal>

      {/* Delete Confirmation */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => { setShowDeleteConfirm(false); setUserToDelete(null) }}
        title={t('users.deleteUserConfirmTitle')}
        isConfirm
        danger
        confirmText={t('users.deleteUser')}
        onConfirm={confirmDelete}
      >
        {t('users.deleteConfirm')} <strong>{userToDelete?.name}</strong>
      </Modal>
    </div>
  )
}
