'use client'

import { ReactNode, useMemo, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { useRouter } from 'next/navigation'
import { useQueryClient } from '@tanstack/react-query'
import Alert from '@mui/material/Alert'
import Avatar from '@mui/material/Avatar'
import Button from '@mui/material/Button'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Chip from '@mui/material/Chip'
import CircularProgress from '@mui/material/CircularProgress'
import Collapse from '@mui/material/Collapse'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Paper from '@mui/material/Paper'
import Typography from '@mui/material/Typography'
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Skeleton from '@mui/material/Skeleton'
import Tooltip from '@mui/material/Tooltip'

import { CATEGORIES_LIST_QUERY_KEY, useGetCategoryInfo, useGetCategoriesList } from '@/@core/hooks/data/categories'
import type { ICategory } from '@/types/data/categories/category.interface'
import AddCategoryDrawer from './addCategoryDrawer'
import EditCategoryDrawer from './EditCategoryDrawer'
import DeleteCategoryDialog from './DeleteCategoryDialog'

type CategoryDetailsProps = {
  categoryId: string
}

const CategoryDetails = ({ categoryId }: CategoryDetailsProps) => {
  const t = useTranslations('categories.details')
  const tableT = useTranslations('categories.table')
  const locale = useLocale()
  const router = useRouter()
  const queryClient = useQueryClient()
  const numberFormatter = useMemo(() => new Intl.NumberFormat(locale === 'ar' ? 'ar-SA' : 'en-US'), [locale])

  const { data: categoryResponse, isLoading: categoryLoading, isError: categoryError } = useGetCategoryInfo(categoryId)

  const [addDrawerState, setAddDrawerState] = useState<{ open: boolean; parentId: string | null }>({
    open: false,
    parentId: categoryId
  })
  const [editDrawerState, setEditDrawerState] = useState<{
    open: boolean
    categoryId?: string
    parentId?: string | null
  }>({
    open: false,
    categoryId: undefined,
    parentId: undefined
  })
  const [deleteState, setDeleteState] = useState<{
    open: boolean
    categoryId?: string
    parentId?: string | null
  }>({
    open: false,
    categoryId: undefined,
    parentId: undefined
  })
  const [subSectionExpanded, setSubSectionExpanded] = useState(false)

  const handleOpenAddDrawer = (parent?: string | null) => {
    setAddDrawerState({ open: true, parentId: parent ?? categoryId })
  }

  const handleCloseAddDrawer = () => {
    setAddDrawerState(prev => ({ ...prev, open: false }))
  }

  const handleOpenEditDrawer = (targetId: string, parentId?: string | null) => {
    setEditDrawerState({ open: true, categoryId: targetId, parentId })
  }

  const handleCloseEditDrawer = () => {
    setEditDrawerState({ open: false, categoryId: undefined })
  }

  const handleOpenDeleteDialog = (targetId: string, parentId?: string | null) => {
    setDeleteState({ open: true, categoryId: targetId, parentId })
  }

  const handleCloseDeleteDialog = () => {
    setDeleteState({ open: false, categoryId: undefined })
  }

  const invalidateCategoryBranch = (parentId?: string | null) => {
    const normalizedParentId = parentId ?? categoryId

    queryClient.invalidateQueries({
      predicate: query => {
        if (query.queryKey[0] !== CATEGORIES_LIST_QUERY_KEY) {
          return false
        }

        if (normalizedParentId === undefined) {
          return true
        }

        const [, params] = query.queryKey

        if (!params || typeof params !== 'object') {
          return normalizedParentId === null
        }

        const queryParentId = (params as Record<string, any>).parent_id ?? null

        if (normalizedParentId === null) {
          return queryParentId === null || queryParentId === undefined
        }

        return String(queryParentId ?? '') === String(normalizedParentId)
      }
    })
  }

  const handleRefresh = (options?: { parentId?: string | null; refreshInfo?: boolean }) => {
    const targetParentId = options?.parentId ?? categoryId

    invalidateCategoryBranch(targetParentId)

    if (targetParentId === categoryId || options?.refreshInfo) {
      queryClient.invalidateQueries({ queryKey: ['category-info', categoryId] })
    }
  }

  const handleCategoryDeleted = (parentId?: string | null) => {
    handleCloseDeleteDialog()
    handleRefresh({ parentId, refreshInfo: parentId === categoryId })
  }

  const category = categoryResponse?.data

  const getLocalizedName = (item?: ICategory | null): string => {
    if (!item) {
      return ''
    }

    const value = locale === 'ar' ? item.name_ar : item.name_en

    return value || ''
  }

  const getLocalizedDescription = (item?: ICategory | null): string => {
    if (!item) {
      return ''
    }

    const value = locale === 'ar' ? item.description_ar : item.description_en

    return value || ''
  }

  const renderField = (label: string, value: ReactNode, className = '') => {
    const isPrimitive = typeof value === 'string' || typeof value === 'number'
    const resolvedValue = value === null || value === undefined || value === '' ? '-' : value

    return (
      <Stack className={className} spacing={0.5}>
        <Typography variant='caption' color='text.secondary'>
          {label}
        </Typography>
        {isPrimitive ? <Typography color='text.primary'>{resolvedValue}</Typography> : resolvedValue}
      </Stack>
    )
  }

  if (categoryLoading) {
    return (
      <Stack spacing={4}>
        <Card>
          <CardContent>
            <Stack spacing={3}>
              <Stack direction='row' spacing={3} alignItems='center'>
                <Skeleton variant='circular' width={80} height={80} />
                <div>
                  <Skeleton variant='text' width={200} height={32} />
                  <Skeleton variant='text' width={260} height={20} />
                </div>
              </Stack>
              <Grid container spacing={3}>
                {Array.from({ length: 3 }).map((_, index) => (
                  <Grid size={{ xs: 12, sm: 4 }} key={index}>
                    <Skeleton variant='rounded' height={110} />
                  </Grid>
                ))}
              </Grid>
            </Stack>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Grid container spacing={3}>
              {Array.from({ length: 6 }).map((_, index) => (
                <Grid size={{ xs: 12, sm: 6 }} key={index}>
                  <Skeleton variant='text' height={20} width='35%' />
                  <Skeleton variant='text' height={32} />
                </Grid>
              ))}
            </Grid>
          </CardContent>
        </Card>
      </Stack>
    )
  }

  if (categoryError || !category) {
    return (
      <Alert
        severity='error'
        action={
          <Button color='inherit' size='small' onClick={() => router.push(`/${locale}/categories`)}>
            {t('backToList')}
          </Button>
        }
      >
        {tableT('error')}
      </Alert>
    )
  }

  const parentName = category.parent ? getLocalizedName(category.parent) : t('noParent')
  const localizedName = getLocalizedName(category) || '-'
  const localizedDescription = getLocalizedDescription(category)

  const detailStats = [
    {
      label: t('subCategories'),
      value: numberFormatter.format(category.children_count ?? category.children?.length ?? 0),
      icon: 'tabler-tree'
    },
    {
      label: t('sortOrder'),
      value: category.sort_order ?? '-',
      icon: 'tabler-list-numbers'
    }
  ]

  return (
    <Stack spacing={4}>
      <Card
        sx={{
          background: 'linear-gradient(135deg, #0f172a 0%, #312e81 100%)',
          color: 'common.white'
        }}
      >
        <CardContent>
          <Stack spacing={3}>
            <Stack
              direction={{ xs: 'column', md: 'row' }}
              justifyContent='space-between'
              alignItems={{ xs: 'flex-start', md: 'center' }}
              spacing={2}
            >
              <Stack direction='row' spacing={3} alignItems='center'>
                <Avatar src={category.image_url || undefined} alt={localizedName} sx={{ width: 80, height: 80 }}>
                  {localizedName.charAt(0)}
                </Avatar>
                <div>
                  <Typography variant='h5' className='font-semibold'>
                    {localizedName}
                  </Typography>
                  {localizedDescription && (
                    <Typography variant='body2' sx={{ color: 'rgba(255,255,255,0.8)' }}>
                      {localizedDescription}
                    </Typography>
                  )}
                  <Stack direction='row' spacing={1} mt={1} flexWrap='wrap'>
                    <Chip
                      size='small'
                      color={category.is_active ? 'success' : 'default'}
                      label={category.is_active ? tableT('active') : tableT('inactive')}
                    />
                    <Chip size='small' color='secondary' label={parentName} />
                  </Stack>
                </div>
              </Stack>
              <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
                <Button
                  variant='outlined'
                  onClick={() => router.push(`/${locale}/categories`)}
                  startIcon={<i className='tabler-arrow-left rtl:rotate-180' />}
                  color='inherit'
                >
                  {t('backToList')}
                </Button>
                <Button
                  variant='contained'
                  color='secondary'
                  onClick={() => handleOpenAddDrawer(`${category?.id}`)}
                  startIcon={<i className='tabler-plus' />}
                >
                  {t('addSubCategory')}
                </Button>
              </Stack>
            </Stack>

            <Grid container spacing={3}>
              {detailStats?.map(stat => (
                <Grid size={{ xs: 12, sm: 6 }} key={stat.label}>
                  <Box
                    sx={{
                      p: 3,
                      borderRadius: 3,
                      border: '1px solid rgba(255,255,255,0.15)',
                      backgroundColor: 'rgba(0,0,0,0.25)'
                    }}
                  >
                    <Stack spacing={1.5}>
                      <Box
                        sx={{
                          width: 36,
                          height: 36,
                          borderRadius: '50%',
                          backgroundColor: 'rgba(0,0,0,0.35)',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        <i className={`${stat.icon} text-white text-base`} />
                      </Box>
                      <Typography variant='h6'>{stat.value}</Typography>
                      <Typography variant='body2' sx={{ color: 'rgba(255,255,255,0.7)' }}>
                        {stat.label}
                      </Typography>
                    </Stack>
                  </Box>
                </Grid>
              ))}
            </Grid>
          </Stack>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <Typography variant='h6' className='font-semibold'>
            {t('basicInfo')}
          </Typography>
          <Divider sx={{ my: 4 }} />
          <Grid container spacing={3}>
            {[
              { label: t('nameAr'), value: category.name_ar, icon: 'tabler-language' },
              { label: t('nameEn'), value: category.name_en, icon: 'tabler-language-hiragana' },
              { label: t('parentCategory'), value: parentName, icon: 'tabler-hierarchy' },
              {
                label: t('status'),
                value: (
                  <Chip
                    color={category.is_active ? 'success' : 'default'}
                    label={category.is_active ? tableT('active') : tableT('inactive')}
                  />
                ),
                icon: 'tabler-activity'
              },
              {
                label: t('sortOrder'),
                value: category.sort_order ?? '-',
                icon: 'tabler-list-numbers'
              },
              {
                label: tableT('productsCount'),
                value: numberFormatter.format(category.products_count ?? 0),
                icon: 'tabler-bowl-chopsticks'
              }
            ].map(field => (
              <Grid size={{ xs: 12, sm: 6 }} key={field.label}>
                <Stack direction='row' spacing={2} alignItems='flex-start'>
                  <Box
                    sx={{
                      width: 40,
                      height: 40,
                      borderRadius: '50%',
                      backgroundColor: 'action.hover',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center'
                    }}
                  >
                    <i className={`${field.icon} text-textSecondary`} />
                  </Box>
                  <div className='flex flex-col gap-1'>
                    <Typography variant='caption' color='text.secondary'>
                      {field.label}
                    </Typography>
                    {typeof field.value === 'string' || typeof field.value === 'number' ? (
                      <Typography>{field.value || '-'}</Typography>
                    ) : (
                      field.value
                    )}
                  </div>
                </Stack>
              </Grid>
            ))}
          </Grid>
          <Divider sx={{ my: 4 }} />
          <Grid container spacing={3}>
            {[
              { label: t('descriptionAr'), value: category.description_ar },
              { label: t('descriptionEn'), value: category.description_en }
            ].map(desc => (
              <Grid size={{ xs: 12, sm: 6 }} key={desc.label}>
                <Typography variant='caption' color='text.secondary'>
                  {desc.label}
                </Typography>
                <Typography variant='body2' color='text.primary'>
                  {desc.value || '-'}
                </Typography>
              </Grid>
            ))}
          </Grid>
        </CardContent>
      </Card>

      <Card>
        <CardContent>
          <div className='flex flex-wrap items-center justify-between gap-3 mb-4'>
            <div>
              <Typography variant='h6' className='font-semibold'>
                {t('subCategories')}
              </Typography>
            </div>
            <div className='flex items-center gap-2'>
              <Typography variant='body2' color='text.secondary'>
                {t('subSectionHint')}
              </Typography>
              <Button
                variant='text'
                size='small'
                onClick={() => setSubSectionExpanded(prev => !prev)}
                startIcon={<i className={`tabler-chevron-${subSectionExpanded ? 'up' : 'down'}`} />}
              >
                {subSectionExpanded ? t('collapseTree') : t('expandTree')}
              </Button>
            </div>
          </div>

          {subSectionExpanded ? (
            <CategoryChildrenList
              parentId={`${category.id}`}
              depth={0}
              tableT={tableT}
              detailsT={t}
              getLocalizedName={getLocalizedName}
              getLocalizedDescription={getLocalizedDescription}
              onAddChild={handleOpenAddDrawer}
              onEditChild={(id, parentId) => handleOpenEditDrawer(id, parentId)}
              onDeleteChild={(id, parentId) => handleOpenDeleteDialog(id, parentId)}
              expanded={subSectionExpanded}
            />
          ) : (
            <Typography color='text.secondary'>{t('expandTree')}</Typography>
          )}
        </CardContent>
      </Card>

      <AddCategoryDrawer
        open={addDrawerState.open}
        handleClose={handleCloseAddDrawer}
        onAdded={() => handleRefresh({ parentId: addDrawerState.parentId ?? String(category.id) })}
        parentId={addDrawerState.parentId ?? String(category.id)}
        disableParentSelection
      />

      <EditCategoryDrawer
        open={editDrawerState.open}
        handleClose={handleCloseEditDrawer}
        categoryId={editDrawerState.categoryId}
        onUpdated={() => handleRefresh({ parentId: editDrawerState.parentId ?? categoryId })}
      />

      <DeleteCategoryDialog
        open={deleteState.open}
        handleClose={handleCloseDeleteDialog}
        categoryId={deleteState.categoryId}
        onDeleted={() => handleCategoryDeleted(deleteState.parentId)}
      />
    </Stack>
  )
}

type TranslateFn = (key: string) => string

type LocalizeFn = (item?: ICategory | null) => string

type CategoryTreeItemProps = {
  item: ICategory
  depth: number
  tableT: TranslateFn
  detailsT: TranslateFn
  getLocalizedName: LocalizeFn
  getLocalizedDescription: LocalizeFn
  onAddChild: (parentId: string) => void
  onEditChild: (categoryId: string, parentId?: string | null) => void
  onDeleteChild: (categoryId: string, parentId?: string | null) => void
}

type CategoryChildrenListProps = {
  parentId: string
  depth: number
  tableT: TranslateFn
  detailsT: TranslateFn
  getLocalizedName: LocalizeFn
  getLocalizedDescription: LocalizeFn
  onAddChild: (parentId: string) => void
  onEditChild: (categoryId: string, parentId?: string | null) => void
  onDeleteChild: (categoryId: string, parentId?: string | null) => void
  expanded: boolean
}

const CategoryTreeItem = ({
  item,
  depth,
  tableT,
  detailsT,
  getLocalizedName,
  getLocalizedDescription,
  onAddChild,
  onEditChild,
  onDeleteChild
}: CategoryTreeItemProps) => {
  const [expanded, setExpanded] = useState(false)
  const description = getLocalizedDescription(item)
  const hasKnownChildren = (item.children_count ?? item.children?.length ?? 0) > 0
  const canToggle = hasKnownChildren || depth === 0

  const handleToggle = () => {
    if (!canToggle) return
    setExpanded(prev => !prev)
  }

  const handleAddClick = () => {
    setExpanded(true)
    onAddChild(item?.id)
  }

  return (
    <Paper
      variant='outlined'
      sx={{
        borderColor: 'divider',
        borderRadius: 2,
        p: 3,
        display: 'flex',
        flexDirection: 'column',
        gap: 1.5,
        ml: depth ? depth * 2 : 0,
        backgroundColor: depth % 2 ? 'action.hover' : 'background.paper'
      }}
    >
      <div className='flex flex-wrap items-center justify-between gap-2'>
        <div className='flex items-center gap-2'>
          {canToggle && (
            <IconButton size='small' onClick={handleToggle} className='-ml-2'>
              <i className={`tabler-chevron-${expanded ? 'down' : 'right'} text-textSecondary`} />
            </IconButton>
          )}
          <Typography className='font-medium'>{getLocalizedName(item) || '-'}</Typography>
          <Chip
            size='small'
            color={item.is_active ? 'success' : 'default'}
            variant={item.is_active ? 'filled' : 'outlined'}
            label={item.is_active ? tableT('active') : tableT('inactive')}
          />
          {typeof item.products_count === 'number' && (
            <Chip
              size='small'
              color='primary'
              variant='outlined'
              label={`${tableT('productsCount')}: ${item.products_count}`}
            />
          )}
        </div>
        <div className='flex flex-wrap items-center gap-1'>
          <Tooltip title={detailsT('addChildCategory')}>
            <IconButton size='small' onClick={handleAddClick}>
              <i className='tabler-plus text-textSecondary' />
            </IconButton>
          </Tooltip>
          <Tooltip title={detailsT('editCategory')}>
            <IconButton size='small' onClick={() => onEditChild(`${item?.id}`, item.parent_id ?? null)}>
              <i className='tabler-edit text-textSecondary' />
            </IconButton>
          </Tooltip>
          <Tooltip title={detailsT('deleteCategory')}>
            <IconButton size='small' color='error' onClick={() => onDeleteChild(item.id, item.parent_id ?? null)}>
              <i className='tabler-trash' />
            </IconButton>
          </Tooltip>
        </div>
      </div>
      {description && (
        <Typography variant='body2' color='text.secondary' sx={{ pl: canToggle ? 4.25 : 0 }}>
          {description}
        </Typography>
      )}
      {expanded && (
        <Collapse in={expanded} unmountOnExit>
          <CategoryChildrenList
            parentId={item?.id}
            depth={depth + 1}
            tableT={tableT}
            detailsT={detailsT}
            getLocalizedName={getLocalizedName}
            getLocalizedDescription={getLocalizedDescription}
            onAddChild={onAddChild}
            onEditChild={onEditChild}
            onDeleteChild={onDeleteChild}
            expanded={expanded}
          />
        </Collapse>
      )}
    </Paper>
  )
}

const CategoryChildrenList = ({
  parentId,
  depth,
  tableT,
  detailsT,
  getLocalizedName,
  getLocalizedDescription,
  onAddChild,
  onEditChild,
  onDeleteChild,
  expanded
}: CategoryChildrenListProps) => {
  const shouldFetchChildren = expanded

  const { data, isLoading } = useGetCategoriesList(
    {
      parent_id: parentId
    },
    { enabled: shouldFetchChildren }
  )

  const children = useMemo(() => {
    if (!shouldFetchChildren) {
      return [] as ICategory[]
    }

    const payload = (data as any)?.data

    if (Array.isArray(payload)) {
      return payload as ICategory[]
    }

    if (payload?.data && Array.isArray(payload.data)) {
      return payload.data as ICategory[]
    }

    return [] as ICategory[]
  }, [data, shouldFetchChildren])

  if (!shouldFetchChildren) {
    return null
  }

  if (isLoading && !children.length) {
    return (
      <div className='mt-3 flex items-center gap-2'>
        <CircularProgress size={16} />
        <Typography variant='caption' color='text.secondary'>
          {tableT('loading')}
        </Typography>
      </div>
    )
  }

  if (!children.length) {
    return (
      <Box
        sx={{
          mt: 2,
          ml: depth ? depth * 2 : 0,
          p: 3,
          borderRadius: 2,
          border: '1px dashed',
          borderColor: 'divider',
          backgroundColor: 'action.hover',
          display: 'flex',
          flexDirection: 'column',
          gap: 2
        }}
      >
        <Typography variant='body2' color='text.secondary'>
          {detailsT('noSubCategories')}
        </Typography>
        <Button variant='outlined' size='small' onClick={() => onAddChild(parentId)}>
          <i className='tabler-plus me-1 text-sm' />
          {detailsT('addSubCategory')}
        </Button>
      </Box>
    )
  }

  return (
    <div className='flex flex-col gap-3 mt-3'>
      {children.map(child => (
        <CategoryTreeItem
          key={child.id}
          item={child}
          depth={depth}
          tableT={tableT}
          detailsT={detailsT}
          getLocalizedName={getLocalizedName}
          getLocalizedDescription={getLocalizedDescription}
          onAddChild={onAddChild}
          onEditChild={onEditChild}
          onDeleteChild={onDeleteChild}
        />
      ))}
    </div>
  )
}

export default CategoryDetails
