import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../../core/api/api-client'

const fetchUsers = async () => {
  const res = await apiClient.get('/internal/control-center-users')
  return res.data.data
}

const fetchRoles = async () => {
  const res = await apiClient.get('/internal/roles')
  return res.data.data
}

const createUser = async (data) => {
  const res = await apiClient.post('/internal/control-center-users', data)
  return res.data.data
}

const resetPassword = async ({ id, new_password }) => {
  const res = await apiClient.patch(`/internal/control-center-users/${id}/password`, { new_password })
  return res.data.data
}

// Generate a temporary password that meets backend complexity rules:
// min 8 chars, ≥1 digit, ≥1 uppercase, ≥1 lowercase.
const generateTempPassword = () => {
  const raw = crypto.randomUUID().replace(/-/g, '').slice(0, 12)
  // Ensure uppercase + lowercase + digit — crypto.randomUUID is lowercase hex,
  // so we explicitly prefix to guarantee complexity.
  return `A${raw}9`
}

const errorMessage = (err) => {
  const code = err?.response?.data?.error?.code
  const msg = err?.response?.data?.error?.message
  if (code?.startsWith('PASSWORD_')) return msg || 'Password tidak memenuhi syarat.'
  if (code === 'VALIDATION_ERROR') return msg || 'Input tidak lengkap.'
  if (code === 'EMAIL_ALREADY_EXISTS' || code === 'EMAIL_TAKEN') return 'Email sudah digunakan.'
  return msg || 'Gagal menyimpan.'
}

const ResetPasswordRow = ({ userId }) => {
  const [open, setOpen] = useState(false)
  const [pw, setPw] = useState('')
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  const mutation = useMutation({
    mutationFn: resetPassword,
    onSuccess: () => {
      setSuccess(true)
      setPw('')
    },
    onError: (err) => setError(errorMessage(err)),
  })

  if (!open) {
    return <button onClick={() => { setOpen(true); setSuccess(false); setError('') }}>Reset password</button>
  }

  return (
    <form onSubmit={(e) => { e.preventDefault(); setError(''); mutation.mutate({ id: userId, new_password: pw }) }}
      style={{ display: 'inline-flex', gap: 4, alignItems: 'center' }}>
      <input type="text" placeholder="Password baru" value={pw}
        onChange={e => setPw(e.target.value)} required minLength={8}
        style={{ width: 180 }} />
      <button type="button" onClick={() => setPw(generateTempPassword())}>Generate</button>
      <button type="submit" disabled={mutation.isPending}>
        {mutation.isPending ? '...' : 'Simpan'}
      </button>
      <button type="button" onClick={() => { setOpen(false); setError(''); setSuccess(false) }}>Batal</button>
      {error && <span style={{ color: 'red', fontSize: 12 }}>{error}</span>}
      {success && <span style={{ color: 'green', fontSize: 12 }}>Tersimpan.</span>}
    </form>
  )
}

export default function UsersPage() {
  const queryClient = useQueryClient()
  const { data, isLoading } = useQuery({ queryKey: ['cc-users'], queryFn: fetchUsers })
  const { data: roles } = useQuery({ queryKey: ['roles'], queryFn: fetchRoles })

  const [form, setForm] = useState({ email: '', display_name: '', role_id: '', password: '' })
  const [showForm, setShowForm] = useState(false)
  const [createError, setCreateError] = useState('')

  const createMutation = useMutation({
    mutationFn: createUser,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['cc-users'] })
      setForm({ email: '', display_name: '', role_id: '', password: '' })
      setShowForm(false)
      setCreateError('')
    },
    onError: (err) => setCreateError(errorMessage(err)),
  })

  if (isLoading) return <div>Loading...</div>

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Control Center Users</h1>
        <button onClick={() => { setShowForm(!showForm); setCreateError('') }}>+ Tambah User</button>
      </div>

      {showForm && (
        <form onSubmit={(e) => { e.preventDefault(); setCreateError(''); createMutation.mutate(form) }}
          style={{ marginBottom: 24, padding: 16, border: '1px solid #eee' }}>
          <h3>Tambah User Baru</h3>
          <input placeholder="Email" type="email" value={form.email}
            onChange={e => setForm(f => ({ ...f, email: e.target.value }))} required
            style={{ display: 'block', marginBottom: 8, width: '100%' }} />
          <input placeholder="Nama" value={form.display_name}
            onChange={e => setForm(f => ({ ...f, display_name: e.target.value }))} required
            style={{ display: 'block', marginBottom: 8, width: '100%' }} />
          <select value={form.role_id} onChange={e => setForm(f => ({ ...f, role_id: e.target.value }))} required
            style={{ display: 'block', marginBottom: 8, width: '100%' }}>
            <option value="">Pilih Role</option>
            {roles?.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
          </select>
          <div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
            <input placeholder="Password awal (min 8, huruf besar/kecil + angka)" type="text" value={form.password}
              onChange={e => setForm(f => ({ ...f, password: e.target.value }))} required minLength={8}
              style={{ flex: 1 }} />
            <button type="button" onClick={() => setForm(f => ({ ...f, password: generateTempPassword() }))}>
              Generate
            </button>
          </div>
          <button type="submit" disabled={createMutation.isPending}>
            {createMutation.isPending ? 'Menyimpan...' : 'Simpan'}
          </button>
          {createError && <p style={{ color: 'red' }}>{createError}</p>}
        </form>
      )}

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Nama</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Email</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Role</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Aksi</th>
          </tr>
        </thead>
        <tbody>
          {data?.items?.map((user) => (
            <tr key={user.id}>
              <td style={{ padding: 8 }}>{user.display_name}</td>
              <td style={{ padding: 8 }}>{user.email}</td>
              <td style={{ padding: 8 }}>{user.role?.name}</td>
              <td style={{ padding: 8 }}><ResetPasswordRow userId={user.id} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
