import { Edit } from 'iconsax-react'
import SwitchComponent from '@/components/Switch'
import TrashWithConfrim from '@/components/TrashWithConfrim'
import type { Category } from '../types/Types'

function findCategoryById(cats: Category[], id: string | null): Category | undefined {
  if (!id) return undefined
  for (const c of cats) {
    if (c.id === id) return c
    const found = findCategoryById(c.children || [], id)
    if (found) return found
  }
  return undefined
}

type Props = {
  categories: Category[]
  onStatusChange: (id: string, value: boolean) => void
  onEdit: (category: Category) => void
  onDelete: (id: string) => void
  isDeleting?: boolean
}

const CategoryTableColumns = ({ categories, onStatusChange, onEdit, onDelete, isDeleting = false }: Props) => {
  return [
    {
      title: 'آیکون',
      key: 'avatarUrl',
      render: (item: Category) => (
        <div className="w-8 h-8 rounded-lg flex items-center justify-center overflow-hidden">
          {item.avatarUrl ? (
            <img
              src={item.avatarUrl}
              alt={item.title}
              className="w-full h-full object-cover"
            />
          ) : (
            <div className="w-full h-full bg-gray-200 flex items-center justify-center text-xs">
              بدون آیکون
            </div>
          )}
        </div>
      )
    },
    {
      title: 'عنوان',
      key: 'title',
      render: (item: Category) => (
        <div className={item.parent ? 'pr-6' : ''}>
          {item.title}
        </div>
      )
    },
    {
      title: 'والد',
      key: 'categoryId',
      render: (item: Category) => {
        const parent = typeof item.parent === 'string' ? findCategoryById(categories, item.parent) : item.parent
        return (
          <div>{parent?.title || '-'}</div>
        )
      }
    },
    {
      title: 'وضعیت',
      key: 'isActive',
      render: (item: Category) => (
        <SwitchComponent
          active={item.isActive}
          onChange={(value) => onStatusChange(item.id, value)}
        />
      )
    },
    {
      key: 'actions',
      title: '',
      render: (item: Category) => {
        return (
          <div className='flex gap-2 items-center'>
            <Edit
              onClick={() => onEdit(item)}
              size={20}
              color='#8C90A3'
              className='cursor-pointer'
            />
            <TrashWithConfrim
              onDelete={() => onDelete(item.id)}
              isloading={isDeleting}
            />
          </div>
        )
      }
    }
  ]
}

export default CategoryTableColumns
