import { useAuth } from '@context-providers/auth-context-provider'
import { useTheme } from '@context-providers/theme-context-provider'
import { MoonIcon, PersonIcon, SunIcon } from '@radix-ui/react-icons'

import { toast } from 'sonner'

import { Button } from '@components/ui/button/button'
import { ContentFrame } from '@components/ui/content-frame/content-frame'
import { APP_CONFIG } from '@lib/config'
import { useState } from 'react'
import { Post } from '@types'
import { usePosts } from '@hooks/use-posts'
import { UpdatePostModal } from '@components/forms/post/update'
import { Spreadsheet } from '@components/ui/spreadsheet'
import model from '@components/ui/spreadsheet/model.json'
import type { Model } from '@components/ui/spreadsheet/types'

export const DashboardPage = () => {
  const { logout, user } = useAuth()
  const { theme, setTheme } = useTheme()

  const [selectedPost, setSelectedPost] = useState<Post | null>(null)
  const [isUpdateModalOpen, setIsUpdateModalOpen] = useState(false)

  const onToggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light')
    toast.info("As you may see now it's " + (theme === 'light' ? 'dark' : 'light') + ' theme')
  }
  const { list } = usePosts()

  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 (
    <div className="p-4 h-lvh">
      <ContentFrame
        title={APP_CONFIG.AUTH ? 'Dashboard (authorized route)' : 'Dashboard'}
        controls={[
          <Button key="btn-theme" onClick={onToggleTheme} __e2e_test_id__="button-toggle-theme">
            {theme === 'light' ? <MoonIcon /> : <SunIcon />}
          </Button>,
          APP_CONFIG.AUTH && (
            <Button key="btn-logout" onClick={logout}>
              <PersonIcon /> Logout
            </Button>
          ),
        ]}
      >
        <div className="p-3">
          <h3 className="mb-4">Hi {user?.userDetails?.name}!</h3>
          <p>eMail: {user?.userDetails?.email}</p>
          <p>roles: {user?.userRoles.join(', ')}</p>
        </div>
        <div className="p-3">
          <h3 className="mb-4">Posts:</h3>
          <ul>
            {list
              .toSorted((a, b) => a.id.localeCompare(b.id))
              .map((post) => (
                <li
                  key={post.id}
                  onClick={() => {
                    setSelectedPost(post)
                    setIsUpdateModalOpen(true)
                  }}
                  className="cursor-pointer mb-2 hover:underline"
                >
                  <strong>{post.title}</strong>: {post.body}
                </li>
              ))}
          </ul>
        </div>
        <div className="p-3">
          <Spreadsheet model={model as Model} data={data} />
        </div>
      </ContentFrame>
      <UpdatePostModal
        initial={selectedPost!}
        open={isUpdateModalOpen}
        onClose={() => setIsUpdateModalOpen(false)}
        onSuccess={(updatedPost) => {
          toast.success(`Post "${updatedPost.title}" updated successfully!`)
          setIsUpdateModalOpen(false)
        }}
        onError={(updatedPost, error) => {
          toast.error(`Error updating post "${updatedPost.title}": ${String(error)}`)
        }}
      />
    </div>
  )
}
