import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { UserCheck, UserX, Shield, ArrowRightLeft, ExternalLink, UserPlus, Copy, Check, Mail } from 'lucide-react'
import { DataTable, Pagination, SearchInput, PageHeader, StatusBadge, ActionMenu } from '@/components/admin'
import type { Column } from '@/components/admin'
import { Modal } from '@/components/common/Modal'
import { adminApi } from '@/api/admin'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'

interface AdminUser {
  id: string
  email: string
  name: string
  role: string
  is_super_admin: boolean
  is_active: boolean
  account_id: string | null
  account_role: string | null
  created_at: string
  last_login: string | null
  deleted_at: string | null
}

export function UsersPage() {
  const navigate = useNavigate()
  const [users, setUsers] = useState<AdminUser[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 20
  const [showArchived, setShowArchived] = useState(false)

  // Role change modal
  const [roleModalUser, setRoleModalUser] = useState<AdminUser | null>(null)
  const [newRole, setNewRole] = useState('')

  // Move account modal
  const [moveModalUser, setMoveModalUser] = useState<AdminUser | null>(null)
  const [displayCode, setDisplayCode] = useState('')

  // Create user modal
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [createForm, setCreateForm] = useState({
    email: '',
    name: '',
    account_mode: 'personal' as 'existing' | 'personal',
    account_display_code: '',
    account_role: 'engineer' as 'engineer' | 'viewer',
    send_email: true,
  })
  const [createLoading, setCreateLoading] = useState(false)

  // Temp password display modal
  const [tempPassword, setTempPassword] = useState<string | null>(null)
  const [copied, setCopied] = useState(false)

  // Invite user modal
  const [showInviteModal, setShowInviteModal] = useState(false)
  const [inviteForm, setInviteForm] = useState({ email: '', account_display_code: '', role: 'engineer' as 'engineer' | 'viewer' })
  const [inviteLoading, setInviteLoading] = useState(false)

  const fetchUsers = useCallback(async () => {
    setLoading(true)
    try {
      const data = await adminApi.listUsers({ page, size: pageSize, search: search || undefined, include_archived: showArchived || undefined })
      setUsers(data.items || data)
      setTotal(data.total || (data.items ? data.items.length : data.length))
    } catch {
      toast.error('Failed to load users')
    } finally {
      setLoading(false)
    }
  }, [page, search, showArchived])

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

  const handleRoleChange = async () => {
    if (!roleModalUser || !newRole) return
    try {
      await adminApi.updateUserRole(roleModalUser.id, newRole)
      toast.success('Role updated')
      setRoleModalUser(null)
      fetchUsers()
    } catch {
      toast.error('Failed to update role')
    }
  }

  const handleToggleActive = async (user: AdminUser) => {
    try {
      if (user.is_active) {
        await adminApi.deactivateUser(user.id)
        toast.success('User deactivated')
      } else {
        await adminApi.activateUser(user.id)
        toast.success('User activated')
      }
      fetchUsers()
    } catch {
      toast.error('Failed to update user status')
    }
  }

  const handleMoveAccount = async () => {
    if (!moveModalUser || !displayCode) return
    try {
      await adminApi.moveUserAccount(moveModalUser.id, displayCode)
      toast.success('User moved to account')
      setMoveModalUser(null)
      setDisplayCode('')
      fetchUsers()
    } catch {
      toast.error('Failed to move user')
    }
  }

  const handleCreateUser = async () => {
    if (!createForm.email || !createForm.name) return
    if (createForm.account_mode === 'existing' && !createForm.account_display_code) {
      toast.error('Account display code is required')
      return
    }
    setCreateLoading(true)
    try {
      const result = await adminApi.createUser({
        email: createForm.email,
        name: createForm.name,
        account_mode: createForm.account_mode,
        account_display_code: createForm.account_mode === 'existing' ? createForm.account_display_code : undefined,
        account_role: createForm.account_mode === 'existing' ? createForm.account_role : undefined,
        send_email: createForm.send_email,
      })
      setShowCreateModal(false)
      setTempPassword(result.temporary_password)
      setCopied(false)
      toast.success(result.email_sent ? 'User created and welcome email sent' : 'User created')
      setCreateForm({ email: '', name: '', account_mode: 'personal', account_display_code: '', account_role: 'engineer', send_email: true })
      fetchUsers()
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { detail?: string } } }
        toast.error(axiosErr.response?.data?.detail || 'Failed to create user')
      } else {
        toast.error('Failed to create user')
      }
    } finally {
      setCreateLoading(false)
    }
  }

  const handleCopyPassword = async () => {
    if (!tempPassword) return
    await navigator.clipboard.writeText(tempPassword)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleInviteUser = async () => {
    if (!inviteForm.email || !inviteForm.account_display_code) return
    setInviteLoading(true)
    try {
      const result = await adminApi.createInvite({
        email: inviteForm.email,
        account_display_code: inviteForm.account_display_code,
        role: inviteForm.role,
      })
      setShowInviteModal(false)
      setInviteForm({ email: '', account_display_code: '', role: 'engineer' })
      toast.success(result.email_sent ? 'Invite sent' : 'Invite created (email not configured)')
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { detail?: string } } }
        toast.error(axiosErr.response?.data?.detail || 'Failed to send invite')
      } else {
        toast.error('Failed to send invite')
      }
    } finally {
      setInviteLoading(false)
    }
  }

  const columns: Column<AdminUser>[] = [
    {
      key: 'name',
      header: 'Name',
      sortable: true,
      render: (u) => (
        <div>
          <div className="font-medium text-foreground">{u.name}</div>
          <div className="text-xs text-muted-foreground">{u.email}</div>
        </div>
      ),
    },
    {
      key: 'role',
      header: 'Role',
      render: (u) => (
        <div className="flex items-center gap-2">
          <span className="text-sm">{u.role}</span>
          {u.is_super_admin && (
            <StatusBadge variant="destructive">Super Admin</StatusBadge>
          )}
        </div>
      ),
    },
    {
      key: 'status',
      header: 'Status',
      render: (u) => (
        <div className="flex items-center gap-1">
          <StatusBadge variant={u.is_active ? 'success' : 'destructive'}>
            {u.is_active ? 'Active' : 'Inactive'}
          </StatusBadge>
          {u.deleted_at && (
            <StatusBadge variant="warning">Archived</StatusBadge>
          )}
        </div>
      ),
    },
    {
      key: 'created_at',
      header: 'Joined',
      sortable: true,
      render: (u) => (
        <span className="text-sm text-muted-foreground">
          {new Date(u.created_at).toLocaleDateString()}
        </span>
      ),
    },
    {
      key: 'actions',
      header: '',
      className: 'w-12',
      render: (u) => (
        <ActionMenu items={[
          {
            label: 'View Detail',
            icon: <ExternalLink className="h-4 w-4" />,
            onClick: () => navigate(`/admin/users/${u.id}`),
          },
          {
            label: 'Change Role',
            icon: <Shield className="h-4 w-4" />,
            onClick: () => { setRoleModalUser(u); setNewRole(u.role) },
          },
          {
            label: u.is_active ? 'Deactivate' : 'Activate',
            icon: u.is_active ? <UserX className="h-4 w-4" /> : <UserCheck className="h-4 w-4" />,
            onClick: () => handleToggleActive(u),
            destructive: u.is_active,
          },
          {
            label: 'Move Account',
            icon: <ArrowRightLeft className="h-4 w-4" />,
            onClick: () => { setMoveModalUser(u); setDisplayCode('') },
          },
        ]} />
      ),
    },
  ]

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <PageHeader title="Users" description="Manage platform users and roles" />
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowInviteModal(true)}
            className="flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-accent transition-colors"
          >
            <Mail className="h-4 w-4" />
            Invite User
          </button>
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex items-center gap-2 rounded-lg bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 transition-colors"
          >
            <UserPlus className="h-4 w-4" />
            Create User
          </button>
        </div>
      </div>

      <div className="flex items-center gap-4">
        <SearchInput
          value={search}
          onSearch={(v) => { setSearch(v); setPage(1) }}
          placeholder="Search by name or email..."
          className="max-w-sm"
        />
        <label className="flex items-center gap-2 text-sm text-muted-foreground">
          <input
            type="checkbox"
            checked={showArchived}
            onChange={(e) => { setShowArchived(e.target.checked); setPage(1) }}
            className="rounded border-border bg-card"
          />
          Show archived
        </label>
      </div>

      <DataTable
        columns={columns}
        data={users}
        keyExtractor={(u) => u.id}
        isLoading={loading}
      />

      <Pagination
        page={page}
        totalPages={Math.ceil(total / pageSize)}
        total={total}
        pageSize={pageSize}
        onPageChange={setPage}
      />

      {/* Role Change Modal */}
      <Modal
        isOpen={!!roleModalUser}
        onClose={() => setRoleModalUser(null)}
        title="Change Role"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button
              onClick={() => setRoleModalUser(null)}
              className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground/60 hover:bg-accent hover:text-foreground"
            >
              Cancel
            </button>
            <button
              onClick={handleRoleChange}
              className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90"
            >
              Save
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Changing role for <span className="font-medium text-foreground">{roleModalUser?.name}</span>
          </p>
          <select
            value={newRole}
            onChange={(e) => setNewRole(e.target.value)}
            className={cn(
              'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
              'focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
            )}
          >
            <option value="engineer">Engineer</option>
            <option value="viewer">Viewer</option>
          </select>
        </div>
      </Modal>

      {/* Move Account Modal */}
      <Modal
        isOpen={!!moveModalUser}
        onClose={() => setMoveModalUser(null)}
        title="Move User to Account"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button
              onClick={() => setMoveModalUser(null)}
              className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground/60 hover:bg-accent hover:text-foreground"
            >
              Cancel
            </button>
            <button
              onClick={handleMoveAccount}
              disabled={!displayCode}
              className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50"
            >
              Move
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Moving <span className="font-medium text-foreground">{moveModalUser?.name}</span> to a new account.
          </p>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Account Display Code</label>
            <input
              type="text"
              value={displayCode}
              onChange={(e) => setDisplayCode(e.target.value)}
              placeholder="e.g. ABC-1234"
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            />
          </div>
        </div>
      </Modal>

      {/* Create User Modal */}
      <Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="Create User"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button
              onClick={() => setShowCreateModal(false)}
              className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground/60 hover:bg-accent hover:text-foreground"
            >
              Cancel
            </button>
            <button
              onClick={handleCreateUser}
              disabled={createLoading || !createForm.email || !createForm.name}
              className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50"
            >
              {createLoading ? 'Creating...' : 'Create User'}
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Name</label>
            <input
              type="text"
              value={createForm.name}
              onChange={(e) => setCreateForm(f => ({ ...f, name: e.target.value }))}
              placeholder="Full name"
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Email</label>
            <input
              type="email"
              value={createForm.email}
              onChange={(e) => setCreateForm(f => ({ ...f, email: e.target.value }))}
              placeholder="user@example.com"
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Account Mode</label>
            <select
              value={createForm.account_mode}
              onChange={(e) => setCreateForm(f => ({ ...f, account_mode: e.target.value as 'existing' | 'personal' }))}
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            >
              <option value="personal">Personal (new account)</option>
              <option value="existing">Join existing account</option>
            </select>
          </div>
          {createForm.account_mode === 'existing' && (
            <>
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">Account Display Code</label>
                <input
                  type="text"
                  value={createForm.account_display_code}
                  onChange={(e) => setCreateForm(f => ({ ...f, account_display_code: e.target.value }))}
                  placeholder="e.g. ABC12345"
                  className={cn(
                    'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                    'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
                  )}
                />
              </div>
              <div>
                <label className="mb-1 block text-sm font-medium text-foreground">Account Role</label>
                <select
                  value={createForm.account_role}
                  onChange={(e) => setCreateForm(f => ({ ...f, account_role: e.target.value as 'engineer' | 'viewer' }))}
                  className={cn(
                    'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                    'focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
                  )}
                >
                  <option value="engineer">Engineer</option>
                  <option value="viewer">Viewer</option>
                </select>
              </div>
            </>
          )}
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              id="send-email"
              checked={createForm.send_email}
              onChange={(e) => setCreateForm(f => ({ ...f, send_email: e.target.checked }))}
              className="rounded border-border bg-card"
            />
            <label htmlFor="send-email" className="text-sm text-muted-foreground">
              Send welcome email with temporary password
            </label>
          </div>
        </div>
      </Modal>

      {/* Temporary Password Modal */}
      <Modal
        isOpen={!!tempPassword}
        onClose={() => setTempPassword(null)}
        title="User Created"
        size="sm"
        footer={
          <div className="flex justify-end">
            <button
              onClick={() => setTempPassword(null)}
              className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90"
            >
              Done
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <div className="rounded-xl border border-yellow-400/20 bg-yellow-400/10 p-3 text-sm text-yellow-400">
            This password will not be shown again. Copy it now.
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Temporary Password</label>
            <div className="flex items-center gap-2">
              <code className="flex-1 rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground font-mono">
                {tempPassword}
              </code>
              <button
                onClick={handleCopyPassword}
                className="rounded-md border border-border p-2 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
                title="Copy password"
              >
                {copied ? <Check className="h-4 w-4 text-green-400" /> : <Copy className="h-4 w-4" />}
              </button>
            </div>
          </div>
          <p className="text-xs text-muted-foreground">
            The user will be required to change this password on first login.
          </p>
        </div>
      </Modal>

      {/* Invite User Modal */}
      <Modal
        isOpen={showInviteModal}
        onClose={() => setShowInviteModal(false)}
        title="Invite User"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <button
              onClick={() => setShowInviteModal(false)}
              className="rounded-md border border-border px-4 py-2 text-sm font-medium text-foreground/60 hover:bg-accent hover:text-foreground"
            >
              Cancel
            </button>
            <button
              onClick={handleInviteUser}
              disabled={inviteLoading || !inviteForm.email || !inviteForm.account_display_code}
              className="rounded-md bg-gradient-brand text-white shadow-lg shadow-primary/20 px-4 py-2 text-sm font-medium hover:opacity-90 disabled:opacity-50"
            >
              {inviteLoading ? 'Sending...' : 'Send Invite'}
            </button>
          </div>
        }
      >
        <div className="space-y-4">
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Email</label>
            <input
              type="email"
              value={inviteForm.email}
              onChange={(e) => setInviteForm(f => ({ ...f, email: e.target.value }))}
              placeholder="user@example.com"
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Account Display Code</label>
            <input
              type="text"
              value={inviteForm.account_display_code}
              onChange={(e) => setInviteForm(f => ({ ...f, account_display_code: e.target.value }))}
              placeholder="e.g. ABC12345"
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'placeholder:text-muted-foreground focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            />
          </div>
          <div>
            <label className="mb-1 block text-sm font-medium text-foreground">Role</label>
            <select
              value={inviteForm.role}
              onChange={(e) => setInviteForm(f => ({ ...f, role: e.target.value as 'engineer' | 'viewer' }))}
              className={cn(
                'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
                'focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20'
              )}
            >
              <option value="engineer">Engineer</option>
              <option value="viewer">Viewer</option>
            </select>
          </div>
        </div>
      </Modal>
    </div>
  )
}

export default UsersPage
