import { DashboardLayout } from '@/frontend/components/DashboardLayout'
import { StatsCard } from '@/frontend/components/StatsCard'
import {
  ActionIcon,
  Avatar,
  Badge,
  Box,
  Button,
  Card,
  Container,
  Divider,
  Group,
  List,
  Loader,
  Modal,
  Pagination,
  Paper,
  PasswordInput,
  Select,
  SimpleGrid,
  Stack,
  Table,
  Tabs,
  Text,
  TextInput,
  ThemeIcon,
  Title,
  Tooltip,
} from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { notifications } from '@mantine/notifications'
import { createFileRoute } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import {
  TbAccessPoint,
  TbCircleCheck,
  TbCircleX,
  TbPencil,
  TbPlus,
  TbSearch,
  TbShieldCheck,
  TbTrash,
  TbUserCheck,
  TbUserPlus,
  TbUsers,
} from 'react-icons/tb'
import useSWR from 'swr'
import { API_URLS } from '../config/api'
import { useSession } from '../hooks/useAuth'

export const Route = createFileRoute('/users')({
  component: UsersPage,
})

const fetcher = (url: string) => fetch(url).then((res) => res.json())

const ROLE_COLOR: Record<string, string> = {
  DEVELOPER: 'violet',
  ADMIN: 'brand-blue',
  USER: 'gray',
}
const ROLE_LABEL: Record<string, string> = {
  DEVELOPER: 'Developer',
  ADMIN: 'Admin',
  USER: 'User',
}

const roles = [
  {
    name: 'DEVELOPER',
    color: 'violet',
    description: 'Super admin with full system access, including the Dev Console.',
    permissions: [
      'Access Dev Console (/dev)',
      'User & role management',
      'Manage bug reports & feedback',
      'View all apps & activity logs',
      'Manage app versions & status',
      'Delete system logs',
    ],
  },
  {
    name: 'ADMIN',
    color: 'blue',
    description: 'Operator who can manage applications, bugs, and view activity logs.',
    permissions: [
      'View & manage all applications',
      'Manage bug reports',
      'View activity logs',
      'View user, village, and order data',
      'Update village & product status',
    ],
  },
  {
    name: 'USER',
    color: 'gray',
    description: 'New account pending approval. Awaiting review by an Admin or Developer.',
    permissions: [
      'Access profile page',
      'View account approval status',
    ],
  },
]

function UsersPage() {
  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [page, setPage] = useState(1)
  const { data: session } = useSession()
  const isDeveloper = session?.user?.role === 'DEVELOPER'

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300)
    return () => clearTimeout(timer)
  }, [search])

  const { data: stats, mutate: mutateStats } = useSWR(API_URLS.getOperatorStats(), fetcher)
  const { data: response, isLoading, mutate: mutateOperators } = useSWR(
    API_URLS.getOperators(page, debouncedSearch),
    fetcher,
  )

  const operators = response?.data || []

  // ── Create User Modal ──
  const [createOpened, { open: openCreate, close: closeCreate }] = useDisclosure(false)
  const [isCreating, setIsCreating] = useState(false)
  const [createForm, setCreateForm] = useState({ name: '', email: '', password: '', role: 'ADMIN' })

  const handleCreateUser = async () => {
    if (!createForm.name || !createForm.email || !createForm.password) {
      notifications.show({ title: 'Validation Error', message: 'Please fill in all required fields.', color: 'red' })
      return
    }
    setIsCreating(true)
    try {
      const res = await fetch(API_URLS.createOperator(), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(createForm),
      })
      if (res.ok) {
        notifications.show({ title: 'Success', message: 'User has been created.', color: 'teal', icon: <TbCircleCheck size={18} /> })
        mutateOperators()
        mutateStats()
        closeCreate()
        setCreateForm({ name: '', email: '', password: '', role: 'ADMIN' })
      } else {
        const err = await res.json()
        throw new Error(err.error || 'Failed to create user')
      }
    } catch (e: any) {
      notifications.show({ title: 'Error', message: e.message || 'Something went wrong.', color: 'red', icon: <TbCircleX size={18} /> })
    } finally {
      setIsCreating(false)
    }
  }

  // ── Edit User Modal ──
  const [editOpened, { open: openEdit, close: closeEdit }] = useDisclosure(false)
  const [isEditing, setIsEditing] = useState(false)
  const [editingUserId, setEditingUserId] = useState<string | null>(null)
  const [editForm, setEditForm] = useState({ name: '', email: '', role: '' })

  const handleOpenEdit = (user: any) => {
    setEditingUserId(user.id)
    setEditForm({ name: user.name, email: user.email, role: user.role })
    openEdit()
  }

  const handleEditUser = async () => {
    if (!editingUserId || !editForm.name || !editForm.email) return
    setIsEditing(true)
    try {
      const res = await fetch(API_URLS.editOperator(editingUserId), {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editForm),
      })
      if (res.ok) {
        notifications.show({ title: 'Success', message: 'User has been updated.', color: 'teal', icon: <TbCircleCheck size={18} /> })
        mutateOperators()
        closeEdit()
      } else {
        throw new Error('Failed to update user')
      }
    } catch {
      notifications.show({ title: 'Error', message: 'Something went wrong.', color: 'red', icon: <TbCircleX size={18} /> })
    } finally {
      setIsEditing(false)
    }
  }

  // ── Delete User Modal ──
  const [deleteOpened, { open: openDelete, close: closeDelete }] = useDisclosure(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [deletingUser, setDeletingUser] = useState<any>(null)

  const handleOpenDelete = (user: any) => {
    setDeletingUser(user)
    openDelete()
  }

  const handleDeleteUser = async () => {
    if (!deletingUser) return
    setIsDeleting(true)
    try {
      const res = await fetch(API_URLS.deleteOperator(deletingUser.id), { method: 'DELETE' })
      if (res.ok) {
        notifications.show({ title: 'Success', message: 'User has been deleted.', color: 'teal', icon: <TbCircleCheck size={18} /> })
        mutateOperators()
        mutateStats()
        closeDelete()
      } else {
        const err = await res.json()
        throw new Error(err.error || 'Failed to delete user')
      }
    } catch (e: any) {
      notifications.show({ title: 'Error', message: e.message || 'Something went wrong.', color: 'red', icon: <TbCircleX size={18} /> })
    } finally {
      setIsDeleting(false)
    }
  }

  // ── Activate User ──
  const handleActivateUser = async (user: any) => {
    try {
      const res = await fetch(`/api/operators/${user.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ active: true }),
      })
      if (res.ok) {
        notifications.show({ title: 'Success', message: `${user.name} has been reactivated.`, color: 'teal', icon: <TbCircleCheck size={18} /> })
        mutateOperators()
        mutateStats()
      } else {
        const err = await res.json()
        throw new Error(err.error || 'Failed to activate user')
      }
    } catch (e: any) {
      notifications.show({ title: 'Error', message: e.message || 'Something went wrong.', color: 'red', icon: <TbCircleX size={18} /> })
    }
  }

  return (
    <DashboardLayout>
      <Container size="xl" py="lg">
        <Stack gap="xl">
          <Stack gap={4}>
            <Title order={2} className="gradient-text">User Management</Title>
            <Text size="sm" c="dimmed">Manage platform users, security roles, and access control.</Text>
          </Stack>

          <SimpleGrid cols={{ base: 1, sm: 3 }} spacing="lg">
            <StatsCard
              title="Total Staff"
              value={stats?.totalStaff ?? 0}
              description="Registered platform users"
              icon={TbUserCheck}
              color="brand-blue"
            />
            <StatsCard
              title="Active Now"
              value={stats?.activeNow ?? 0}
              description="Users with active sessions"
              icon={TbAccessPoint}
              color="teal"
            />
            <StatsCard
              title="Security Roles"
              value={stats?.rolesCount ?? 0}
              description="Defined permission levels"
              icon={TbShieldCheck}
              color="purple-primary"
            />
          </SimpleGrid>

          <Tabs defaultValue="users" color="brand-blue" variant="pills" radius="md">
            <Tabs.List>
              <Tabs.Tab value="users" leftSection={<TbUserCheck size={16} />}>User Management</Tabs.Tab>
              <Tabs.Tab value="roles" leftSection={<TbShieldCheck size={16} />}>Role Reference</Tabs.Tab>
            </Tabs.List>

            <Tabs.Panel value="users" pt="xl">
              <Stack gap="md">
                <Group justify="space-between">
                  <TextInput
                    placeholder="Search by name or email..."
                    leftSection={<TbSearch size={16} />}
                    radius="md"
                    w={320}
                    variant="filled"
                    value={search}
                    onChange={(e) => { setSearch(e.currentTarget.value); setPage(1) }}
                  />
                  {isDeveloper && (
                    <Button
                      variant="gradient"
                      gradient={{ from: '#2563EB', to: '#7C3AED', deg: 135 }}
                      leftSection={<TbPlus size={18} />}
                      radius="md"
                      size="sm"
                      onClick={openCreate}
                    >
                      Add New User
                    </Button>
                  )}
                </Group>

                <Paper withBorder radius="2xl" className="glass" p={0} style={{ overflow: 'hidden' }}>
                  <Table className="data-table" verticalSpacing="md" highlightOnHover>
                    <Table.Thead>
                      <Table.Tr>
                        <Table.Th>Name & Contact</Table.Th>
                        <Table.Th>Role</Table.Th>
                        <Table.Th>Joined</Table.Th>
                        <Table.Th>Actions</Table.Th>
                      </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>
                      {isLoading ? (
                        <Table.Tr>
                          <Table.Td colSpan={4}>
                            <Group justify="center" py="xl">
                              <Loader size="sm" type="dots" />
                            </Group>
                          </Table.Td>
                        </Table.Tr>
                      ) : operators.length === 0 ? (
                        <Table.Tr>
                          <Table.Td colSpan={4}>
                            <Stack align="center" gap="xs" py="xl">
                              <TbUsers size={32} style={{ opacity: 0.25 }} />
                              <Text size="sm" c="dimmed">No users found.</Text>
                            </Stack>
                          </Table.Td>
                        </Table.Tr>
                      ) : (
                        operators.map((user: any) => (
                          <Table.Tr key={user.id}>
                            <Table.Td style={{ opacity: user.active === false ? 0.45 : 1 }}>
                              <Group gap="sm">
                                <Box style={{ position: 'relative' }}>
                                  <Avatar
                                    size="sm"
                                    radius="xl"
                                    color={user.active === false ? 'gray' : ROLE_COLOR[user.role] ?? 'gray'}
                                    src={user.image}
                                  >
                                    {user.name.charAt(0)}
                                  </Avatar>
                                  {user.active === false && (
                                    <Box
                                      style={{
                                        position: 'absolute', bottom: -2, right: -2,
                                        width: 10, height: 10, borderRadius: '50%',
                                        background: 'var(--mantine-color-red-6)',
                                        border: '1.5px solid var(--mantine-color-body)',
                                      }}
                                    />
                                  )}
                                </Box>
                                <Stack gap={0}>
                                  <Group gap={6}>
                                    <Text fw={600} size="sm" c={user.active === false ? 'dimmed' : undefined}>
                                      {user.name}
                                    </Text>
                                    {user.active === false && (
                                      <Badge size="xs" color="red" variant="light">Inactive</Badge>
                                    )}
                                  </Group>
                                  <Text size="xs" c="dimmed">{user.email}</Text>
                                </Stack>
                              </Group>
                            </Table.Td>
                            <Table.Td style={{ opacity: user.active === false ? 0.45 : 1 }}>
                              <Badge
                                variant="light"
                                size="sm"
                                color={user.active === false ? 'gray' : ROLE_COLOR[user.role] ?? 'gray'}
                              >
                                {ROLE_LABEL[user.role] ?? user.role}
                              </Badge>
                            </Table.Td>
                            <Table.Td style={{ opacity: user.active === false ? 0.45 : 1 }}>
                              <Text size="xs" fw={500} c={user.active === false ? 'dimmed' : undefined}>
                                {new Date(user.createdAt).toLocaleDateString('en-GB', {
                                  day: 'numeric',
                                  month: 'short',
                                  year: 'numeric',
                                })}
                              </Text>
                            </Table.Td>
                            <Table.Td>
                              <Group gap="xs">
                                {user.active === false ? (
                                  <Tooltip label="Reactivate user" withArrow>
                                    <ActionIcon
                                      disabled={!isDeveloper}
                                      variant="light"
                                      size="sm"
                                      color="teal"
                                      onClick={() => handleActivateUser(user)}
                                    >
                                      <TbUserPlus size={14} />
                                    </ActionIcon>
                                  </Tooltip>
                                ) : (
                                  <>
                                    <Tooltip label="Edit user" withArrow>
                                      <ActionIcon
                                        disabled={!isDeveloper}
                                        variant="light"
                                        size="sm"
                                        color="blue"
                                        onClick={() => handleOpenEdit(user)}
                                      >
                                        <TbPencil size={14} />
                                      </ActionIcon>
                                    </Tooltip>
                                    <Tooltip label="Delete user" withArrow>
                                      <ActionIcon
                                        disabled={!isDeveloper}
                                        variant="light"
                                        size="sm"
                                        color="red"
                                        onClick={() => handleOpenDelete(user)}
                                      >
                                        <TbTrash size={14} />
                                      </ActionIcon>
                                    </Tooltip>
                                  </>
                                )}
                              </Group>
                            </Table.Td>
                          </Table.Tr>
                        ))
                      )}
                    </Table.Tbody>
                  </Table>
                </Paper>

                {response?.totalPages > 1 && (
                  <Group justify="center" mt="md">
                    <Pagination total={response.totalPages} value={page} onChange={setPage} size="sm" radius="md" />
                  </Group>
                )}
              </Stack>
            </Tabs.Panel>

            <Tabs.Panel value="roles" pt="xl">
              <SimpleGrid cols={{ base: 1, md: 3 }} spacing="lg">
                {roles.map((role) => (
                  <Card key={role.name} withBorder radius="2xl" padding="xl" className="glass">
                    <Stack gap="md">
                      <ThemeIcon size="xl" radius="md" color={role.color} variant="light">
                        <TbShieldCheck size={28} />
                      </ThemeIcon>

                      <Stack gap={4}>
                        <Title order={4}>{ROLE_LABEL[role.name] ?? role.name}</Title>
                        <Text size="sm" c="dimmed">{role.description}</Text>
                      </Stack>

                      <Divider />

                      <Text size="xs" fw={700} c="dimmed" tt="uppercase">Key Permissions</Text>
                      <List
                        spacing="xs"
                        size="sm"
                        center
                        icon={
                          <ThemeIcon color="teal" size={16} radius="xl">
                            <TbCircleCheck size={12} />
                          </ThemeIcon>
                        }
                      >
                        {role.permissions.map((p) => (
                          <List.Item key={p}>{p}</List.Item>
                        ))}
                      </List>
                    </Stack>
                  </Card>
                ))}
              </SimpleGrid>
            </Tabs.Panel>
          </Tabs>
        </Stack>
      </Container>

      {/* Create User Modal */}
      <Modal
        opened={createOpened}
        onClose={closeCreate}
        title={<Text fw={700} size="lg">Add New User</Text>}
        radius="md"
        overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
      >
        <Stack gap="md">
          <TextInput
            label="Full Name"
            placeholder="Enter full name"
            required
            value={createForm.name}
            onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
          />
          <TextInput
            label="Email"
            placeholder="Enter email address"
            required
            value={createForm.email}
            onChange={(e) => setCreateForm({ ...createForm, email: e.target.value })}
          />
          <PasswordInput
            label="Password"
            placeholder="Enter password"
            required
            value={createForm.password}
            onChange={(e) => setCreateForm({ ...createForm, password: e.target.value })}
          />
          <Select
            label="Role"
            data={[
              { value: 'ADMIN', label: 'Admin' },
              { value: 'DEVELOPER', label: 'Developer' },
            ]}
            value={createForm.role}
            onChange={(val) => setCreateForm({ ...createForm, role: val || 'ADMIN' })}
          />
          <Button
            fullWidth
            mt="md"
            variant="gradient"
            gradient={{ from: '#2563EB', to: '#7C3AED', deg: 135 }}
            loading={isCreating}
            onClick={handleCreateUser}
          >
            Create User
          </Button>
        </Stack>
      </Modal>

      {/* Edit User Modal */}
      <Modal
        opened={editOpened}
        onClose={closeEdit}
        title={<Text fw={700} size="lg">Edit User</Text>}
        radius="md"
        overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
      >
        <Stack gap="md">
          <TextInput
            label="Full Name"
            placeholder="Enter full name"
            required
            value={editForm.name}
            onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
          />
          <TextInput
            label="Email"
            placeholder="Enter email address"
            required
            value={editForm.email}
            onChange={(e) => setEditForm({ ...editForm, email: e.target.value })}
          />
          <Select
            label="Role"
            data={[
              { value: 'USER', label: 'User (Pending)' },
              { value: 'ADMIN', label: 'Admin' },
              { value: 'DEVELOPER', label: 'Developer' },
            ]}
            value={editForm.role}
            onChange={(val) => setEditForm({ ...editForm, role: val || 'ADMIN' })}
          />
          <Button
            fullWidth
            mt="md"
            variant="gradient"
            gradient={{ from: '#2563EB', to: '#7C3AED', deg: 135 }}
            loading={isEditing}
            onClick={handleEditUser}
          >
            Save Changes
          </Button>
        </Stack>
      </Modal>

      {/* Delete Confirmation Modal */}
      <Modal
        opened={deleteOpened}
        onClose={closeDelete}
        title={<Text fw={700} size="lg">Delete User</Text>}
        radius="md"
        size="sm"
        overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
      >
        <Stack gap="md">
          <Text size="sm">
            Are you sure you want to delete{' '}
            <Text component="span" fw={700}>{deletingUser?.name}</Text>?
            This action cannot be undone.
          </Text>
          <Group justify="flex-end" mt="md">
            <Button variant="subtle" color="gray" onClick={closeDelete}>Cancel</Button>
            <Button color="red" loading={isDeleting} onClick={handleDeleteUser}>Delete User</Button>
          </Group>
        </Stack>
      </Modal>
    </DashboardLayout>
  )
}
