import * as React from 'react';

import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuSeparator,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuTrigger,
} from '@/components/ui/context-menu';
import {
  MobileTable as KonstaTable,
  MobileTableBody as KonstaTableBody,
  MobileTableCell as KonstaTableCell,
  MobileTableHead as KonstaTableHead,
  MobileTableRow as KonstaTableRow,
} from '@/components/ui/mobile';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';

import { MenuData } from '../AnyDropdownMenu';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

function Table({ className, ...props }: React.ComponentProps<"table">) {

  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTable data-slot="table" className={cn("caption-bottom text-sm", className)} {...props} />
    )
  }

  return (
    <table
      data-slot="table"
      className={cn("caption-bottom text-sm", className)}
      {...props}
    />
  )
}

function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {

  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTableHead data-slot="table-header" className={cn("[&_tr]:border-b", className)} {...props} />
    )
  }
  return (
    <thead
      data-slot="table-header"
      className={cn("[&_tr]:border-b", className)}
      {...props}
    />
  )
}

function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTableBody data-slot="table-body" className={cn("[&_tr:last-child]:border-0", className)} {...props} />
    )
  }
  return (
    <tbody
      data-slot="table-body"
      className={cn("[&_tr:last-child]:border-0", className)}
      {...props}
    />
  )
}

function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
  return (
    <tfoot
      data-slot="table-footer"
      className={cn(
        "bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
        className
      )}
      {...props}
    />
  )
}


const ContextMenuRender = ({ menu }: { menu: MenuData[] }) => {

  return menu.map((item) => {
    if (item.type === 'separator') {
      return <ContextMenuSeparator key={item.key} />
    }

    if (item.submenu) {

      return <ContextMenuSub>
        <ContextMenuSubTrigger>{item.label}</ContextMenuSubTrigger>
        <ContextMenuSubContent>
          <ContextMenuRender menu={item.submenu} />
        </ContextMenuSubContent>
      </ContextMenuSub>

    } else {
      return <ContextMenuItem

        onClick={() => item.click?.()}
        key={item.key}>{item.htmlIcon} {item.label}</ContextMenuItem>
    }
  })
}

function TableRow({ className, header, contextMenuItems, onContextMenuOpen, contextMenuLoading, ...props }: React.ComponentProps<"tr"> & { header?: boolean, contextMenuItems?: MenuData[], onContextMenuOpen?: () => void, contextMenuLoading?: boolean }) {

  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTableRow
        header={header}
        data-slot="table-row" className={cn("[&_tr]:border-b", className)} {...props} />
    )
  }

  const hasContextMenu = (contextMenuItems && contextMenuItems.length > 0) || !!onContextMenuOpen || !!contextMenuLoading;

  if (!isMobile && hasContextMenu) {
    return <ContextMenu onOpenChange={(open) => { if (open) onContextMenuOpen?.(); }}>
      <ContextMenuTrigger asChild>
        <tr
          data-slot="table-row"
          className={cn(
            "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
            className
          )}
          {...props}
        />
      </ContextMenuTrigger>
      <ContextMenuContent>
        {contextMenuLoading ? (
          <div className="flex flex-col gap-1 p-1">
            <Skeleton className="h-7 w-36" />
            <Skeleton className="h-7 w-28" />
            <Skeleton className="h-7 w-24" />
          </div>
        ) : (
          <ContextMenuRender menu={contextMenuItems ?? []} />
        )}
      </ContextMenuContent>
    </ContextMenu>
  }
  return (
    <tr
      data-slot="table-row"
      className={cn(
        "hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
        className
      )}
      {...props}
    />
  )
}

function TableHead({ className, ...props }: React.ComponentProps<"th">) {

  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTableCell data-slot="table-head" className={cn("[&_tr]:border-b", className)} {...props} />
    )
  }
  return (
    <th
      data-slot="table-head"
      className={cn(
        "text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
        className
      )}
      {...props}
    />
  )
}

function TableCell({ className, ...props }: React.ComponentProps<"td">) {
  const { isMobile } = useAppConfigStore();

  if (isMobile) {
    return (
      <KonstaTableCell

        data-slot="table-cell" className={cn("[&_tr]:border-b", className)} {...props} />
    )
  }
  return (
    <td
      data-slot="table-cell"
      className={cn(
        "p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
        className
      )}
      {...props}
    />
  )
}

function TableCaption({
  className,
  ...props
}: React.ComponentProps<"caption">) {
  return (
    <caption
      data-slot="table-caption"
      className={cn("text-muted-foreground mt-4 text-sm", className)}
      {...props}
    />
  )
}

export {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
};
