import React from 'react'

import Button from '../Button/Button'
import MdashCheck from '../Mdash/MdashCheck'
import Tag from '../Tag/Tag'
import { toast } from '../Toast/Toast'
import { type TagColorList } from '../Tag/Tag'

export const color: TagColorList[] = [
  'blue',
  'red',
  'green',
  'yellow',
  'royal-blue',
  'teal',
  'pink',
  'orange',
  'gray',
]

export type TableObjectType = {
  id: number
  name: string
  tag: string
  number: number
  decimal: number
  percent: number
  currency: number
  localCurrency?: number
  availability?: number
  conversion?: number
  price?: number
  loyalty?: number
  traffic?: number
  link: string
  string: string
  phaseKey?: string
  isGroupHeader?: boolean
  groupNum?: number
  sortProp?: string
}

export const generateSampleData = () => {
  const records: Array<TableObjectType> = []

  for (let i = 0; i < 100; i++) {
    const record = {
      id: i + 1,
      name: `Record ${i + 1}`,
      tag: `Tag ${i + 1}`,
      number: i + 1,
      decimal: (i + 1) * 0.5,
      percent: (i + 1) * 0.1,
      currency: (i + 1) * 1000,
      link: `https://example.com/${i + 1}`,
      string: `String ${i + 1}`,
      availability: (i + 2) * 0.1,
      traffic: i + 2,
      conversion: (i + 2) * 0.5,
      price: i * 100,
      loyalty: (i + 1) * 0.5,
    }

    records.push(record)
  }
  return records
}

export const generateRandomSampleData = () => {
  const records: Array<TableObjectType> = []

  for (let i = 0; i < 100; i++) {
    const record = {
      id: i + 1,
      name: `Record ${Math.floor(Math.random() * 9901) + 100}`,
      tag: `Tag ${Math.floor(Math.random() * 9901) + 100}`,
      number: Math.floor(Math.random() * 9901) + 100,
      decimal: Math.random() * 100,
      percent: Math.random() * 100,
      currency: Math.floor(Math.random() * 100) * 1000,
      string: `String ${Math.floor(Math.random() * 9901) + 100}`,
      link: '', // added link property to satisfy TableObjectType
    }

    records.push(record)
  }
  return records
}

export const standardTableSampleData = generateSampleData()

export const extraTableSampleData = [
  {
    id: 1001,
    number: 2,
    decimal: 3.0,
    percent: 0.17,
    currency: 4000,
    lastColumn: (
      <Button
        styleType='primary'
        onClick={() => {
          toast({ message: 'Action clicked', type: 'success' })
        }}
      >
        Action
      </Button>
    ),
    isGroupHeader: true,
    displayHeaderData: true,
    groupNum: 1,
    tag: null,
  },
  {
    id: 2001,
    number: 26,
    decimal: 6.13,
    percent: 0.25,
    currency: 9876 + 12345,
    lastColumn: (
      <div
        style={{ height: '36px', fontSize: '8px' }}
      >{`{use empty div for equal row height spacing, 36px}`}</div>
    ),
    isGroupHeader: true,
    displayHeaderData: true,
    groupNum: 2,
    tag: null,
  },
]

export const generateGroupAccordionSampleData = () => {
  const records: Array<TableObjectType> = []

  for (let i = 0; i < 100; i++) {
    const isGroupHeader = (i + 1) % 3 === 0
    const record = {
      id: i + 1,
      name: `Record ${i + 1}`,
      tag: `Tag ${i + 1}`,
      number: i + 1,
      decimal: (i + 1) * 0.5,
      percent: (i + 1) * 0.1,
      currency: (i + 1) * 1000,
      link: `https://example.com/${i + 1}`,
      string: `String ${i + 1}`,
      phaseKey: `name${(i + 1) % 5 === 0 ? 2 : 1}`,
      groupDataKey: `name${(i + 1) % 5 === 0 ? 2 : 1}`,
      isGroupHeader: isGroupHeader ? true : undefined,
      groupNum: i + 1,
    }

    records.push(record)
  }
  return records
}
export const groupAccordionSampleData = generateGroupAccordionSampleData()

export const getCellData = (type: string, d: TableObjectType, i?: number) => {
  switch (type) {
    case 'name':
      return (
        <div className={d.sortProp === 'name' ? 'font-semibold' : ''}>
          {d.name}
        </div>
      )
    case 'tag':
      return (
        <>
          {d?.tag && (
            <Tag
              color={
                i ? color[i % 9] : color[Math.floor(Math.random() * 8) + 1]
              }
            >
              {d.tag}
            </Tag>
          )}
          {!d?.tag && <div style={{ width: '40px' }} />}
        </>
      )
    case 'number':
      return (
        <div className={d.sortProp === 'number' ? 'font-semibold' : ''}>
          {d.number}
        </div>
      )
    case 'decimal':
      return (
        <div className={d.sortProp === 'decimal' ? 'font-semibold' : ''}>
          {d?.decimal?.toFixed(2)}
        </div>
      )
    case 'percent':
      return (
        <MdashCheck check={!!d.percent}>
          <span
            className={d.sortProp === 'percent' ? 'font-semibold' : ''}
          >{`${(d?.percent * 100).toFixed(0)}%`}</span>
        </MdashCheck>
      )
    case 'currency':
      return (
        <div className={d.sortProp === 'currency' ? 'font-semibold' : ''}>
          ${(d.currency || 0).toLocaleString()}
        </div>
      )
    case 'localCurrency':
      return (
        <div className={d.sortProp === 'localCurrency' ? 'font-semibold' : ''}>
          ${(d.localCurrency || 0).toLocaleString()}
        </div>
      )
    case 'string':
      return (
        <div className={d.sortProp === 'string' ? 'font-semibold' : ''}>
          {d.string}
        </div>
      )
    case 'availability':
      return (
        <MdashCheck check={!!d.availability}>
          <span
            className={d.sortProp === 'availability' ? 'font-semibold' : ''}
          >{`${((d.availability ?? 0) * 100).toFixed(0)}%`}</span>
        </MdashCheck>
      )
    case 'traffic':
      return (
        <div className={d.sortProp === 'traffic' ? 'font-semibold' : ''}>
          {d.traffic}
        </div>
      )
    case 'conversion':
      return (
        <MdashCheck check={!!d.conversion}>
          <span
            className={d.sortProp === 'conversion' ? 'font-semibold' : ''}
          >{`${((d.conversion ?? 0) * 100).toFixed(0)}%`}</span>
        </MdashCheck>
      )
    case 'price':
      return (
        <div className={d.sortProp === 'price' ? 'font-semibold' : ''}>
          ${(d.price || 0).toLocaleString()}
        </div>
      )
    case 'loyalty':
      return (
        <MdashCheck check={!!d.loyalty}>
          <span
            className={d.sortProp === 'loyalty' ? 'font-semibold' : ''}
          >{`${((d.loyalty ?? 0) * 100).toFixed(0)}%`}</span>
        </MdashCheck>
      )
    case 'link':
      return (
        <Button as='link' routerComponent='a' href={d.link}>
          Button Link
        </Button>
      )
  }
}

const columnsWithFilter = [
  'Number',
  'Decimal',
  'Percent',
  'Currency',
  'Availability',
  'Traffic',
  'Conversion',
  'Price',
  'Loyalty',
]
const percentColumns = ['Percent', 'Availability', 'Conversion', 'Loyalty']
const currencyColumns = ['Currency', 'Price']
const longTooltipContent =
  'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diam nisl sit amet erat. Duis semper. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Pellentesque congue. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque sed dui ut augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae...'

export const generateTableConfig = (
  columns: Array<string>,
  isAllColumnsNoSort: boolean,
  withFilterProps = false,
  isLongTooltip?: boolean,
) => {
  const records: Array<{
    label: string
    name: string
    mainColumn?: boolean
    noSort?: boolean
    isButton?: boolean
    cell: {
      children: (d: TableObjectType, j?: number) => void
    }
  }> = []

  for (let i = 0; i < columns.length; i++) {
    const name = `${columns[i].toLowerCase()}`
    const label = columns[i]

    const record = {
      label: columns[i] === 'Link' ? '' : columns[i],
      name: columns[i] === 'Link' ? '' : name,
      ...(i === 0 ? { mainColumn: true } : {}),
      ...(isAllColumnsNoSort
        ? { noSort: true }
        : ['Link', 'Tag', 'Percent'].includes(columns[i])
          ? { noSort: true }
          : {}),
      ...(columns[i] === 'Link' ? { isButton: true } : {}),
      ...(['Tag', 'Currency'].includes(columns[i])
        ? {
            beta: true,
            tooltip: {
              content: isLongTooltip ? longTooltipContent : 'tooltip',
              ...(isLongTooltip && { maxWidth: '500px' }),
            },
          }
        : {}),
      cell: {
        children: (d: TableObjectType, j?: number) => {
          return getCellData(name, d, j)
        },
      },
      ...(withFilterProps && columnsWithFilter.includes(label)
        ? {
            options: [{ name, label }],
            filter: {
              type: 'number',
              headerText: label,
              tableKey: name,
              secondarySortProp: name,
              disabled: false,
              ...(percentColumns.includes(label)
                ? { textFieldType: 'percentage' }
                : currencyColumns.includes(label)
                  ? { textFieldType: 'currency', currencySymbol: '$' }
                  : {}),
            },
          }
        : {}),
    }

    records.push(record)
  }
  return records
}

export const tableConfig = generateTableConfig(
  ['Name', 'Tag', 'Number', 'Decimal', 'Percent', 'Currency', 'String'],
  false,
)

export const nestedTableSampleData = {
  1: [
    {
      id: 1.1,
      name: 'Sub 1',
      tag: 'sub-1',
      number: 1,
      decimal: 1.0,
      percent: 0.12,
      currency: 2275,
    },
    {
      id: 1.2,
      name: 'Sub 2',
      tag: 'sub-2',
      number: 1,
      decimal: 2.0,
      percent: 0.05,
      currency: 1725,
    },
  ],
  2: [
    {
      id: 2.1,
      name: 'Sub 1',
      tag: 'nested-1',
      number: 1,
      decimal: 1.0,
      currency: 2275,
    },
    {
      id: 2.2,
      name: 'Sub 2',
      tag: 'nested-2',
      number: 1,
      decimal: 2.0,
      currency: 1725,
    },
    {
      id: 2.3,
      name: 'Sub 3',
      tag: 'nested-3',
      number: 6,
      decimal: 0.14,
      currency: 5876,
    },
  ],
}
type SubCategory = {
  id: number
  name: string
  tag: string
  number: number
  decimal: number
  percent: number
  currency: number
  subCategory?: SubCategory[]
}

function createSubCategory(
  id: number,
  level: number,
  tagSuffix: number,
): SubCategory {
  const subCategory: SubCategory = {
    id: id,
    name: `${level}th Nested Row`,
    tag: `sub-${tagSuffix}`,
    number: Math.floor(Math.random() * 100),
    decimal: parseFloat((Math.random() * 10).toFixed(2)),
    percent: parseFloat(Math.random().toFixed(2)),
    currency: Math.floor(Math.random() * 10000),
  }

  if (level < 4) {
    // Adjust depth here
    subCategory.subCategory = [
      createSubCategory(id + 1, level + 1, tagSuffix + 1),
    ]
    if (level < 3) {
      // Example condition to add more subcategories
      subCategory.subCategory.push(
        createSubCategory(id + 2, level + 1, tagSuffix + 1),
      )
    }
  }

  return subCategory
}

function createCategory(id: number, tag: string): SubCategory {
  return {
    id: id,
    name: '1st Nested Row',
    tag: tag,
    number: Math.floor(Math.random() * 100),
    decimal: parseFloat((Math.random() * 10).toFixed(2)),
    percent: parseFloat(Math.random().toFixed(2)),
    currency: Math.floor(Math.random() * 10000),
    subCategory: [createSubCategory(id + 1, 2, 1)],
  }
}

export const multiNestedTableSampleData = {
  999: [
    createCategory(1001, 'sub-1'),
    createCategory(1003, 'sub-2'),
    createCategory(1008, 'sub-1'),
  ],
  ...nestedTableSampleData,
}

export const nestedRowStylingData = {
  1: [
    {
      id: 1.1,
      name: 'Nested Row 1',
      tag: 'nested-1',
      number: 100,
      decimal: 1.0,
      percent: 0.12,
      currency: 2275,
      rowClassName: 'bgc-light-red',
    },
    {
      id: 1.2,
      name: 'Nested Row 2',
      tag: 'nested-2',
      number: 200,
      decimal: 2.0,
      percent: 0.05,
      currency: 1725,
      rowClassName: 'bgc-light-purple',
    },
  ],
  2: [
    {
      id: 2.1,
      name: 'Nested Row 1',
      tag: 'sub-1',
      number: 150,
      decimal: 1.5,
      currency: 3000,
      rowClassName: 'bgc-light-yellow',
    },
    {
      id: 2.2,
      name: 'Nested Row 2',
      tag: 'sub-2',
      number: 250,
      decimal: 2.5,
      currency: 4500,
      rowClassName: 'bgc-light-green',
    },
  ],
  3: [
    {
      id: 3.1,
      name: 'Nested Row 1',
      tag: 'child-1',
      number: 300,
      decimal: 3.0,
      currency: 5000,
      rowClassName: 'bgc-light-blue',
    },
  ],
}
