import type { ColumnDef } from '@tanstack/vue-table'
import { h, ref } from 'vue'
import { Users, Car, Building, Package, MoreHorizontal, Edit, ListTodo, Trash2, ArrowUpDown, ArrowUp, ArrowDown, ChevronDown } from 'lucide-vue-next'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'

import EditableTaskStatus from './EditableTaskStatus.vue'
import TaskStatusBadge from '@/components/task/TaskStatusBadge.vue'
import { type Asset, AssetCategory, AssetStatus, TaskStatus } from '@/services/asset'

// Helper function to get the appropriate sort icon
const getSortIcon = (sortDirection: false | 'asc' | 'desc') => {
  if (sortDirection === 'asc') {
    return h(ArrowDown, { class: 'ml-2 h-4 w-4' })
  } else if (sortDirection === 'desc') {
    return h(ArrowUp, { class: 'ml-2 h-4 w-4' })
  } else {
    return h(ArrowUpDown, { class: 'ml-2 h-4 w-4' })
  }
}

// Helper function to get category icon
const getCategoryIcon = (category: AssetCategory) => {
  switch (category) {
    case AssetCategory.CHARACTERS:
      return Users
    case AssetCategory.PROPS:
      return Package
    case AssetCategory.SETS:
      return Building
    case AssetCategory.VEHICLES:
      return Car
    default:
      return Package
  }
}

export interface AssetColumnMeta {
  projectId: number
  categories: Array<{ value: string; label: string; icon: any }>
  onEdit: (asset: Asset) => void
  onDelete: (asset: Asset) => void
  onViewTasks: (asset: Asset) => void
  onTaskStatusUpdated: (assetId: number, taskType: string, newStatus: TaskStatus) => void
  onBulkTaskStatusChange?: (taskType: string, status: TaskStatus) => void
  getSelectedCount?: () => number
  getAllStatusOptions?: () => Array<{ id: string; name: string; color?: string; is_system?: boolean }>
}

export const createAssetColumns = (
  allTaskTypes: string[],
  meta: AssetColumnMeta
): ColumnDef<Asset>[] => {
  const columns: ColumnDef<Asset>[] = [
    // Select column
    {
      id: 'select',
      header: ({ table }) =>
        h(Checkbox, {
          modelValue: table.getIsAllPageRowsSelected(),
          'onUpdate:modelValue': (value: boolean | 'indeterminate') => table.toggleAllPageRowsSelected(value === true),
          ariaLabel: 'Select all',
        }),
      cell: ({ row }) =>
        h(Checkbox, {
          modelValue: row.getIsSelected(),
          'onUpdate:modelValue': (value: boolean | 'indeterminate') => row.toggleSelected(value === true),
          ariaLabel: 'Select row',
          onClick: (e: Event) => e.stopPropagation(),
        }),
      enableSorting: false,
      enableHiding: false,
    },
    // Thumbnail column
    {
      id: 'thumbnail',
      header: 'Thumbnail',
      cell: () => {
        return h('div', { class: 'w-20 h-11 bg-muted flex items-center justify-center' }, [
          h(Package, { class: 'h-6 w-6 text-muted-foreground' }),
        ])
      },
      enableSorting: false,
    },
    // Asset Name column
    {
      accessorKey: 'name',
      header: ({ column }) => {
        return h(
          'div', 
          { class: 'flex items-center justify-center' }, 
          ['Asset Name', getSortIcon(column.getIsSorted())]
        )
      },
      cell: ({ row }) => {
        const asset = row.original
        const CategoryIcon = getCategoryIcon(asset.category)
        return h('div', { class: 'flex items-center gap-2' }, [
          h(CategoryIcon, { class: 'h-4 w-4 text-muted-foreground flex-shrink-0' }),
          h('span', { class: 'font-medium' }, asset.name),
        ])
      },
    },
    // Category column
    {
      accessorKey: 'category',
      header: ({ column }) => {
        return h(
          'div', 
          { class: 'flex items-center justify-center' }, 
          ['Category', getSortIcon(column.getIsSorted())]
        )
      },
      cell: ({ row }) => {
        const asset = row.original
        const categoryInfo = meta.categories.find(c => c.value === asset.category)
        const label = categoryInfo ? categoryInfo.label : formatCategory(asset.category)
        return h(Badge, { variant: 'outline', class: 'text-xs' }, () => label)
      },
    },
    // Status column
    {
      accessorKey: 'status',
      header: ({ column }) => {
        return h(
          'div', 
          { class: 'flex items-center justify-center' }, 
          ['Status', getSortIcon(column.getIsSorted())]
        )
      },
      cell: ({ row }) => {
        const asset = row.original
        const variant = getStatusVariant(asset.status)
        const label = formatStatus(asset.status)
        return h(Badge, { variant, class: 'text-xs' }, () => label)
      },
    },
  ]

  // Add task status columns dynamically
  allTaskTypes.forEach((taskType) => {
    // Create ref for popover state for each task type
    const isPopoverOpen = ref(false)
    
    columns.push({
      accessorKey: `task_status.${taskType}`,
      id: taskType,
      header: ({ column }) => {
        const selectedCount = meta.getSelectedCount?.() || 0
        
        if (selectedCount > 0) {
          return h('div', { class: 'flex items-center gap-2' }, [
            h(
              'div',
              { class: 'flex items-center justify-center' },
              [formatTaskType(taskType), getSortIcon(column.getIsSorted())]
            ),
            h('div', { onClick: (e: Event) => e.stopPropagation() }, [
              h(Popover, {
                open: isPopoverOpen.value,
                'onUpdate:open': (value: boolean) => { isPopoverOpen.value = value }
              }, {
                default: () => [
                  h(PopoverTrigger, {}, {
                    default: () => h(
                      Button,
                      {
                        variant: 'outline',
                        size: 'sm',
                        class: 'h-6 w-6 p-0',
                      },
                      () => h(ChevronDown, { class: 'h-3 w-3' })
                    ),
                  }),
                  h(PopoverContent, { class: 'w-48 p-2', align: 'start' }, {
                    default: () => {
                      // Get task statuses from meta
                      const allStatusOptions = meta.getAllStatusOptions?.() || []
                      
                      return h('div', { class: 'flex flex-col gap-1' }, [
                        h('div', { class: 'px-2 py-1.5 text-sm font-semibold' }, `Change ${formatTaskType(taskType)} Status`),
                        ...allStatusOptions.map((statusOption) =>
                          h(
                            Button,
                            {
                              variant: 'ghost',
                              size: 'sm',
                              class: 'justify-start',
                              onClick: () => {
                                meta.onBulkTaskStatusChange?.(taskType, statusOption.id as TaskStatus)
                                isPopoverOpen.value = false
                              },
                            },
                            () => h(TaskStatusBadge, { status: statusOption, compact: true })
                          )
                        ),
                      ])
                    },
                  }),
                ],
              }),
            ]),
          ])
        }
        
        return h(
          'div', 
          { class: 'flex items-center justify-center' }, 
          [formatTaskType(taskType), getSortIcon(column.getIsSorted())]
        )
      },
      cell: ({ row }) => {
        const asset = row.original
        const status = asset.task_status?.[taskType] || TaskStatus.NOT_STARTED
        const taskId = asset.task_details?.find(t => t.task_type === taskType)?.task_id
        
        return h(EditableTaskStatus, {
          key: `${asset.id}-${taskType}`, // Add stable key to prevent unnecessary re-renders
          assetId: asset.id,
          taskType,
          status,
          taskId,
          projectId: meta.projectId,
          onStatusUpdated: (assetId: number, taskType: string, newStatus: TaskStatus) => {
            meta.onTaskStatusUpdated(assetId, taskType, newStatus)
          },
        })
      },
      enableSorting: true,
    })
  })

  // Description column
  columns.push({
    accessorKey: 'description',
    header: ({ column }) => {
      return h(
        'div', 
        { class: 'flex items-center justify-center' }, 
        ['Description', getSortIcon(column.getIsSorted())]
      )
    },
    cell: ({ row }) => {
      const asset = row.original
      return h('span', { class: 'text-sm text-muted-foreground' }, asset.description || '-')
    },
  })

  // Updated At column
  columns.push({
    accessorKey: 'updated_at',
    header: ({ column }) => {
      return h(
        'div', 
        { class: 'flex items-center justify-center' }, 
        ['Updated', getSortIcon(column.getIsSorted())]
      )
    },
    cell: ({ row }) => {
      const asset = row.original
      const date = new Date(asset.updated_at)
      return h('span', { class: 'text-sm text-muted-foreground' }, date.toLocaleDateString())
    },
  })

  // Actions column
  columns.push({
    id: 'actions',
    cell: ({ row }) => {
      const asset = row.original
      return h(
        DropdownMenu,
        {},
        {
          default: () => [
            h(
              DropdownMenuTrigger,
              { 
                asChild: true
              },
              {
                default: () =>
                  h(
                    Button,
                    { 
                      variant: 'ghost', 
                      size: 'sm', 
                      class: 'h-8 w-8 p-0',
                      onMouseDown: (e: Event) => {
                        e.stopPropagation()
                      },
                      onClick: (e: Event) => {
                        e.stopPropagation()
                        e.preventDefault()
                      }
                    },
                    {
                      default: () => h(MoreHorizontal, { class: 'h-4 w-4' }),
                    }
                  ),
              }
            ),
            h(
              DropdownMenuContent,
              { 
                align: 'end'
              },
              {
                default: () => [
                  h(
                    DropdownMenuItem,
                    { 
                      onClick: (e: Event) => { 
                        e.stopPropagation()
                        e.preventDefault()
                        meta.onEdit(asset) 
                      } 
                    },
                    {
                      default: () => [
                        h(Edit, { class: 'h-4 w-4 mr-2' }),
                        'Edit Asset',
                      ],
                    }
                  ),
                  h(
                    DropdownMenuItem,
                    { 
                      onClick: (e: Event) => { 
                        e.stopPropagation()
                        e.preventDefault()
                        meta.onViewTasks(asset) 
                      } 
                    },
                    {
                      default: () => [
                        h(ListTodo, { class: 'h-4 w-4 mr-2' }),
                        'View Tasks',
                      ],
                    }
                  ),
                  h(DropdownMenuSeparator),
                  h(
                    DropdownMenuItem,
                    {
                      onClick: (e: Event) => { 
                        e.stopPropagation()
                        e.preventDefault()
                        meta.onDelete(asset) 
                      },
                      class: 'text-destructive focus:text-destructive',
                    },
                    {
                      default: () => [
                        h(Trash2, { class: 'h-4 w-4 mr-2' }),
                        'Delete Asset',
                      ],
                    }
                  ),
                ],
              }
            ),
          ],
        }
      )
    },
    enableSorting: false,
    enableHiding: false,
  })

  return columns
}

// Helper functions
function formatTaskType(taskType: string): string {
  return taskType.charAt(0).toUpperCase() + taskType.slice(1)
}

function formatCategory(category: AssetCategory): string {
  return category
    .split('_')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

function formatStatus(status: AssetStatus): string {
  return status
    .split('_')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

function getStatusVariant(status: AssetStatus): 'default' | 'secondary' | 'outline' {
  switch (status) {
    case AssetStatus.NOT_STARTED:
      return 'secondary'
    case AssetStatus.IN_PROGRESS:
      return 'default'
    case AssetStatus.ON_HOLD:
      return 'outline'
    case AssetStatus.COMPLETED:
      return 'default'
    case AssetStatus.APPROVED:
      return 'default'
    default:
      return 'secondary'
  }
}