// frontend/src/pages/users/UserForm.jsx

import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import FormField from '@/components/ui/FormField'
import Spinner from '@/components/ui/Spinner'
import Icon from '@/components/ui/Icon'

// ─── Status dual-button ──────────────────────────────────────────────────────

function StatusToggle({ value, onChange }) {
  const opts = [
    { value: 'active',  label: 'Active',  activeBg: 'var(--color-success-bg)', activeFg: 'var(--color-success)'  },
    { value: 'blocked', label: 'Blocked', activeBg: 'var(--color-danger-bg)',  activeFg: 'var(--color-danger)'   },
  ]
  return (
    <div className="flex flex-col" style={{ gap: 'var(--space-2)' }}>
      <span style={{
        fontSize: 'var(--font-size-sm)',
        fontWeight: 'var(--font-weight-medium)',
        color: 'var(--color-text-secondary)',
        lineHeight: 'var(--line-height-tight)',
      }}>
        Status
      </span>
      {/* Match the width of one column in the 2-col grid above */}
      <div style={{ width: 'calc(50% - var(--space-2))' }}>
        <div style={{
          display: 'flex',
          width: '100%',
          borderRadius: 'var(--radius-md)',
          overflow: 'hidden',
          border: '1px solid var(--color-border-strong)',
        }}>
          {opts.map((opt, i) => {
            const active = value === opt.value
            return (
              <button
                key={opt.value}
                type="button"
                onClick={() => onChange(opt.value)}
                style={{
                  flex: 1,
                  padding: 'var(--space-3) var(--space-4)',
                  fontSize: 'var(--font-size-base)',
                  fontWeight: active ? 'var(--font-weight-semibold)' : 'var(--font-weight-normal)',
                  cursor: 'pointer',
                  background: active ? opt.activeBg : 'transparent',
                  color: active ? opt.activeFg : 'var(--color-text-muted)',
                  borderRight: i === 0 ? '1px solid var(--color-border-strong)' : 'none',
                  transition: 'background var(--transition-fast), color var(--transition-fast)',
                  whiteSpace: 'nowrap',
                }}
              >
                {opt.label}
              </button>
            )
          })}
        </div>
      </div>
    </div>
  )
}

// ─── Photo upload field ──────────────────────────────────────────────────────

function PhotoField({ value, onChange, userId }) {
  const fileInputRef              = useRef(null)
  const toast                     = useToast()
  const [uploading, setUploading] = useState(false)
  const [hovered,   setHovered]   = useState(false)

  const handleFileChange = async (e) => {
    const file = e.target.files?.[0]
    if (!file) return
    if (!file.type.startsWith('image/')) {
      toast.danger('Invalid file', 'Please select an image file.')
      return
    }
    setUploading(true)
    try {
      const result = await api.upload(`/users/${userId}/photo`, file)
      onChange(result.url || result.photo_url || '')
      toast.success('Photo updated', 'Profile photo has been uploaded.')
    } catch (err) {
      toast.danger('Upload failed', err.message || 'Could not upload photo.')
    } finally {
      setUploading(false)
      e.target.value = ''
    }
  }

  return (
    <div style={{ display: 'flex', gap: 'var(--space-3)', alignItems: 'stretch' }}>
      {/* Clickable thumbnail — same height as the URL input + hint beside it */}
      <button
        type="button"
        aria-label="Upload profile photo"
        onClick={() => fileInputRef.current?.click()}
        disabled={uploading}
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
        style={{
          position: 'relative',
          flexShrink: 0,
          width: 72,
          borderRadius: 'var(--radius-lg)',
          border: `1px solid ${hovered && !uploading ? 'var(--color-primary)' : 'var(--color-border-strong)'}`,
          overflow: 'hidden',
          cursor: uploading ? 'wait' : 'pointer',
          background: 'var(--color-bg-abyss)',
          transition: 'border-color var(--transition-fast)',
        }}
      >
        {value ? (
          <img
            src={value}
            alt="Profile"
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
            onError={(e) => { e.currentTarget.style.display = 'none' }}
          />
        ) : (
          <div style={{
            width: '100%', height: '100%',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--color-text-muted)',
          }}>
            <Icon name="upload" size={20} />
          </div>
        )}
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: 'rgba(10,14,20,0.60)',
          opacity: uploading || hovered ? 1 : 0,
          transition: 'opacity var(--transition-fast)',
        }}>
          {uploading ? <Spinner size="sm" /> : <Icon name="edit" size={14} color="var(--color-text-primary)" />}
        </div>
      </button>

      <div style={{ flex: 1, minWidth: 0 }}>
        <FormField
          label=""
          name="photo_url"
          type="url"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder="https://..."
          hint="Paste a URL or click the photo to upload a file."
        />
      </div>

      <input ref={fileInputRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleFileChange} />
    </div>
  )
}

// ─── Password section ────────────────────────────────────────────────────────

function EyeToggle({ show, onToggle }) {
  return (
    <button
      type="button"
      aria-label={show ? 'Hide password' : 'Show password'}
      onClick={onToggle}
      style={{
        position: 'absolute',
        right: 'var(--space-3)',
        /* label ~18px + gap 8px = 26px; input height ~36px → centre of input */
        top: 'calc(26px + 18px)',
        transform: 'translateY(-50%)',
        background: 'none',
        border: 'none',
        padding: 0,
        cursor: 'pointer',
        color: 'var(--color-text-muted)',
        display: 'flex',
        alignItems: 'center',
        lineHeight: 1,
        zIndex: 1,
      }}
    >
      <Icon name={show ? 'eye_off' : 'eye'} size={16} />
    </button>
  )
}

function PasswordCard({ userId, hasUid }) {
  const toast                       = useToast()
  const [password,  setPassword]    = useState('')
  const [confirm,   setConfirm]     = useState('')
  const [showPass,  setShowPass]    = useState(false)
  const showConf = showPass
  const [saving,    setSaving]      = useState('')  // 'set' | 'reset' | ''

  const mismatch = confirm && password !== confirm

  const handleSet = async () => {
    if (!password || mismatch) return
    setSaving('set')
    try {
      await api.post(`/users/${userId}/set-password`, { password })
      toast.success('Password updated', 'The new password is active immediately.')
      setPassword('')
      setConfirm('')
    } catch (err) {
      toast.danger('Failed', err.message || 'Could not set password.')
    } finally {
      setSaving('')
    }
  }

  const handleReset = async () => {
    setSaving('reset')
    try {
      await api.post(`/users/${userId}/reset-password`, {})
      toast.success('Password reset', 'Password has been reset to the default.')
    } catch (err) {
      toast.danger('Failed', err.message || 'Could not reset password.')
    } finally {
      setSaving('')
    }
  }

  return (
    <Card title="Firebase Auth Password" variant="flat">
      {!hasUid ? (
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
          This user has no Firebase Auth UID. They must sign up via the app before their password can be managed here.
        </p>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
            Set a new password — active immediately in the mobile app.
          </p>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
            {/* New password */}
            <div style={{ position: 'relative' }}>
              <FormField
                label="New Password"
                name="new_password"
                type={showPass ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Min. 6 characters"
                inputProps={{ style: { paddingRight: 'var(--space-8)' } }}
              />
              <EyeToggle show={showPass} onToggle={() => setShowPass(v => !v)} />
            </div>

            {/* Confirm password */}
            <div style={{ position: 'relative' }}>
              <FormField
                label="Confirm Password"
                name="confirm_password"
                type={showConf ? 'text' : 'password'}
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                placeholder="Re-enter password"
                error={mismatch ? 'Passwords do not match.' : undefined}
                inputProps={{ style: { paddingRight: 'var(--space-8)' } }}
              />
              <EyeToggle show={showConf} onToggle={() => setShowPass(v => !v)} />
            </div>
          </div>

          <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
            <Button
              variant="primary"
              size="sm"
              type="button"
              loading={saving === 'set'}
              disabled={!password || !!mismatch || !!saving}
              onClick={handleSet}
            >
              Set Password
            </Button>
            <Button
              variant="danger"
              size="sm"
              type="button"
              loading={saving === 'reset'}
              disabled={!!saving}
              onClick={handleReset}
            >
              Reset to Default
            </Button>
          </div>
        </div>
      )}
    </Card>
  )
}

// ─── Main ────────────────────────────────────────────────────────────────────

export default function UserForm() {
  const { id }   = useParams()
  const navigate = useNavigate()
  const toast    = useToast()
  const isEdit   = Boolean(id)

  const [form, setForm] = useState({
    email:            '',
    display_name:     '',
    photo_url:        '',
    phone_number:     '',
    status:           'active',
    bio:              '',
    userTitle:        '',
    settingsPIN:      '',
    quickSettingsPIN: '',
  })
  const [uid,     setUid]     = useState('')
  const [loading, setLoading] = useState(false)
  const [saving,  setSaving]  = useState(false)
  const [error,   setError]   = useState('')

  useEffect(() => {
    if (!isEdit) return
    setLoading(true)
    api.get(`/users/${id}`)
      .then((user) => {
        setUid(user.uid || '')
        setForm({
          email:            user.email            || '',
          display_name:     user.display_name     || '',
          photo_url:        user.photo_url         || '',
          phone_number:     user.phone_number      || '',
          status:           user.status            || 'active',
          bio:              user.bio               || '',
          userTitle:        user.userTitle         || '',
          settingsPIN:      user.settingsPIN       || '',
          quickSettingsPIN: user.quickSettingsPIN  || '',
        })
      })
      .catch((err) => {
        setError(err.message)
        toast.danger('Failed to load', err.message)
      })
      .finally(() => setLoading(false))
  }, [id])

  const set    = (key) => (e)   => setForm((f) => ({ ...f, [key]: e.target.value }))
  const setVal = (key) => (val) => setForm((f) => ({ ...f, [key]: val }))
  const setPin = (key) => (e)   => setForm((f) => ({ ...f, [key]: e.target.value.replace(/\D/g, '') }))

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError('')
    setSaving(true)
    try {
      if (isEdit) {
        await api.put(`/users/${id}`, form)
        toast.success('Saved', 'User updated successfully.')
        navigate(`/users/${id}`)
      } else {
        const created = await api.post('/users', form)
        toast.success('Created', `${form.display_name || 'User'} has been added.`)
        navigate(`/users/${created.id}`)
      }
    } catch (err) {
      setError(err.message || 'Something went wrong.')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="page-wrapper page-wrapper--capped">
        <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="lg" />
        </div>
      </div>
    )
  }

  return (
    <div className="page-wrapper page-wrapper--capped">
      <PageHeader
        title={isEdit ? 'Edit User' : 'Add User'}
        subtitle={isEdit ? 'Update account details and profile information' : 'Create a new app user account'}
      >
        <Button variant="ghost" onClick={() => navigate(isEdit ? `/users/${id}` : '/users')}>
          Cancel
        </Button>
        <Button variant="primary" loading={saving} onClick={handleSubmit}>
          {isEdit ? 'Save Changes' : 'Create User'}
        </Button>
      </PageHeader>

      {error && (
        <div style={{
          padding: 'var(--space-3)',
          borderRadius: 'var(--radius-md)',
          backgroundColor: 'var(--color-danger-bg)',
          border: '1px solid var(--color-danger)',
          color: 'var(--color-danger)',
          fontSize: 'var(--font-size-sm)',
        }}>
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} style={{ display: 'contents' }}>
        <div className="masonry-grid masonry-grid--2">

          {/* Account Information */}
          <Card title="Account Information" variant="flat">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
                <FormField
                  label="Email"
                  name="email"
                  type="email"
                  value={form.email}
                  onChange={set('email')}
                  required
                  placeholder="user@example.com"
                />
                <FormField
                  label="Phone Number"
                  name="phone_number"
                  type="tel"
                  value={form.phone_number}
                  onChange={set('phone_number')}
                  placeholder="+1 234 567 8900"
                />
              </div>
              <StatusToggle value={form.status} onChange={setVal('status')} />
            </div>
          </Card>

          {/* Profile */}
          <Card title="Profile" variant="flat">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
              <PhotoField
                value={form.photo_url}
                onChange={setVal('photo_url')}
                userId={isEdit ? id : null}
              />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
                <FormField
                  label="Title"
                  name="userTitle"
                  type="text"
                  value={form.userTitle}
                  onChange={set('userTitle')}
                  placeholder="e.g. Fr, Mr, Miss"
                />
                <FormField
                  label="Display Name"
                  name="display_name"
                  type="text"
                  value={form.display_name}
                  onChange={set('display_name')}
                  required
                  placeholder="e.g. Jane Smith"
                />
              </div>
              <FormField
                label="Bio"
                name="bio"
                type="textarea"
                value={form.bio}
                onChange={set('bio')}
                placeholder="A short description about this user…"
              />
            </div>
          </Card>

          {/* Firebase Auth Password — edit mode only */}
          {isEdit && (
            <PasswordCard userId={id} hasUid={!!uid} />
          )}

          {/* Security — PINs */}
          <Card title="Security" variant="flat">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
              <FormField
                label="Settings PIN"
                name="settingsPIN"
                type="text"
                value={form.settingsPIN}
                onChange={setPin('settingsPIN')}
                placeholder="e.g. 1234"
                hint="Numeric only."
              />
              <FormField
                label="Quick Settings PIN"
                name="quickSettingsPIN"
                type="text"
                value={form.quickSettingsPIN}
                onChange={setPin('quickSettingsPIN')}
                placeholder="e.g. 0000"
                hint="Numeric only."
              />
            </div>
          </Card>

        </div>
      </form>
    </div>
  )
}
