import { AdminSidebarNavContent } from '@admin/admin-sidebar-nav-content'
import { AiSidebarContent } from '@app-actions/ai-sidebar-content'
import { useAuth } from '@context-providers/auth-context-provider'
import { UserViewModel } from '@types'

import { FunnelPlus, ListTree, ScrollText, Sparkles } from 'lucide-react'
import React, { useState } from 'react'
import { toast } from 'sonner'

import { UpdateUserModal } from '@components/forms/user/update'
import { Spreadsheet } from '@components/ui/spreadsheet'
import model from '@components/ui/spreadsheet/model.json'
import type { Model } from '@components/ui/spreadsheet/types'
import { useUsers } from '@hooks/use-users'
import { hasAnyRole } from '@lib/authorization'
import {
  ContentFrame,
  SidebarGroup,
  SidebarGroupContent,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarTab,
} from '@postxl/ui-components'

// ---------------------------------------------------------------------------
// placeholder tab content (only for demo)
// ---------------------------------------------------------------------------
function TabContent({ items }: Readonly<{ items: string[] }>) {
  return (
    <SidebarGroup>
      <SidebarGroupContent>
        <SidebarMenu>
          {items.map((item) => (
            <SidebarMenuItem key={item}>
              <SidebarMenuButton>
                <span>{item}</span>
              </SidebarMenuButton>
            </SidebarMenuItem>
          ))}
        </SidebarMenu>
      </SidebarGroupContent>
    </SidebarGroup>
  )
}

export const DashboardPage = () => {
  const { viewerData } = useAuth()
  const userRoles = viewerData?.userRoles ?? []
  const canAccessAdminPage = hasAnyRole(userRoles, ['admin', 'superadmin'])
  const [selectedUser, setSelectedUser] = useState<UserViewModel | null>(null)
  const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false)

  const { list } = useUsers()

  const data = {
    Sales: [100, null, 110, 120, 130, 140, null, 160, 170, 180, 190, null, 200, 210, 220, 230, null, null],
    COGS: [-10, null, -15, -20, -25, -30, null, -35, -40, -45, -50, null, -55, -60, -65, -70, null, null],
    SGNA: [-20, null, -25, -30, -35, -40, null, -45, -50, -55, -60, null, -65, -70, -75, -80, null, null],
    FTE: [1, null, 2, 3, 4, 5, null, 6, 7, 8, 9, null, 10, 11, 12, 13, null, null],
    // prettier-ignore
    CO2Impact: [1000, null, 1100, 1300, 1400, 1500, null, 1600, 1700, 1800, 1900, null, 2000, 2100, 2200, 2300, null, null],
  }

  return (
    <>
      <ContentFrame title={`Hi ${viewerData?.user?.name}!`}>
        <div className="grid">
          <div className="p-3">
            <p>eMail: {viewerData?.user?.email}</p>
            <p>roles: {viewerData?.userRoles.join(', ')}</p>
          </div>
          <div className="p-3">
            <h3 className="mb-4">Users:</h3>
            <ul>
              {list
                .toSorted((a, b) => a.name.localeCompare(b.name))
                .map((user) => (
                  <li
                    key={user.id}
                    onClick={() => {
                      setSelectedUser(user)
                      setIsUpdateModalOpen(true)
                    }}
                    className="cursor-pointer mb-2 hover:underline"
                  >
                    <strong>{user.name}</strong>: {user.email}
                  </li>
                ))}
            </ul>
          </div>
          <div className="p-3 overflow-auto">
            <Spreadsheet model={model as Model} data={data} />
          </div>
        </div>
      </ContentFrame>
      <UpdateUserModal
        initial={selectedUser!}
        open={isUpdateModalOpen}
        onClose={() => setIsUpdateModalOpen(false)}
        onSuccess={(updatedUser) => {
          toast.success(`User "${updatedUser.name}" updated successfully!`)
          setIsUpdateModalOpen(false)
        }}
        onError={(updatedUser, error) => {
          toast.error(`Error updating user "${updatedUser.name}": ${String(error)}`)
        }}
      />
      <SidebarTab side="left" id="tab-l-1" icon={ListTree} label="Tab 1 label" order={0}>
        <TabContent items={['Lorem ipsum', 'Dolor sit', 'Amet consectetur']} />
      </SidebarTab>
      <SidebarTab side="left" id="tab-l-2" icon={FunnelPlus} label="Tab 2 label" order={1}>
        <TabContent items={['Donec felis neque', 'Tincidunt vel eros', 'Rutrum, porttitor pulvinar']} />
      </SidebarTab>
      {canAccessAdminPage && (
        <SidebarTab side="left" id="tab-l-admin" icon={ScrollText} label="Admin" order={2}>
          <AdminSidebarNavContent />
        </SidebarTab>
      )}
      <SidebarTab side="right" id="ai-assistant-content" icon={Sparkles} label="AI Assistant" order={2}>
        <AiSidebarContent />
      </SidebarTab>
    </>
  )
}
