'use client'

// React Imports
import { useEffect, useState, type ReactElement } from 'react'
import { useSearchParams } from 'next/navigation'

// Next Imports
import dynamic from 'next/dynamic'

// MUI Imports
import Grid from '@mui/material/Grid2'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'

// Type Imports
import type { PricingPlanType } from '@/types/pages/pricingTypes'

// Component Imports
import UserLeftOverview from '@views/apps/user/view/user-left-overview'
import UserRight from '@views/apps/user/view/user-right'

// API Imports
import { userManagementService } from '@/libs/api'
import type { UserDetails } from '@/libs/api/services/userManagementService'

const OverViewTab = dynamic(() => import('@views/apps/user/view/user-right/overview'))
const SecurityTab = dynamic(() => import('@views/apps/user/view/user-right/security'))
const BillingPlans = dynamic(() => import('@views/apps/user/view/user-right/billing-plans'))
const NotificationsTab = dynamic(() => import('@views/apps/user/view/user-right/notifications'))
const ConnectionsTab = dynamic(() => import('@views/apps/user/view/user-right/connections'))

// Vars
const tabContentList = (data?: PricingPlanType[]): { [key: string]: ReactElement } => ({
  overview: <OverViewTab />,
  security: <SecurityTab />,
  'billing-plans': <BillingPlans data={data} />,
  notifications: <NotificationsTab />,
  connections: <ConnectionsTab />
})

const UserViewTab = () => {
  const searchParams = useSearchParams()
  const userId = searchParams.get('id') || '1' // Default to 1 if no ID provided
  const [userData, setUserData] = useState<UserDetails | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchUser = async () => {
      try {
        setLoading(true)
        const user = await userManagementService.getUser(parseInt(userId))
        setUserData(user)
      } catch (err: any) {
        setError(err.message || 'خطا در دریافت اطلاعات کاربر')
        console.error('Error fetching user:', err)
      } finally {
        setLoading(false)
      }
    }
    if (userId) {
      fetchUser()
    }
  }, [userId])

  if (loading) {
    return (
      <Box className='flex items-center justify-center bs-full'>
        <CircularProgress />
      </Box>
    )
  }

  if (error || !userData) {
    return (
      <Box className='flex items-center justify-center bs-full'>
        <Typography color='error'>{error || 'کاربر یافت نشد'}</Typography>
      </Box>
    )
  }

  return (
    <Grid container spacing={6}>
      <Grid size={{ xs: 12, lg: 4, md: 5 }}>
        <UserLeftOverview />
      </Grid>
      <Grid size={{ xs: 12, lg: 8, md: 7 }}>
        <UserRight tabContentList={tabContentList(undefined)} />
      </Grid>
    </Grid>
  )
}

export default UserViewTab
