import { type Meta, type StoryObj } from '@storybook/react-vite'
import React, { useState } from 'react'
import type { ColumnDef } from '@tanstack/react-table'

import { DocsTemplate } from '../../../../.storybook'
import Spreadsheet from './Spreadsheet'
import type { SpreadsheetProps } from './spreadsheet-types-new'
import {
  data,
  editableData,
  exampleSpreadsheetData,
  fewSpreadsheetRows,
  highlightsRowSpreadsheetData,
  manySpreadsheetRows,
} from './StoryHelpers/example-spreadsheet-data-new'
import { editCellColumns } from './StoryHelpers/example-spreadsheet-columns-new'
import { SideDrawer } from '../../SideDrawer/SideDrawer'
import FormFooter from '../../Form/FormFooter'
import Alert from '../../Alerts/Alert'
import TextInput from '../../Form/TextInput'
import { useFocus } from '../../../hooks/useFocus/useFocus'
import PrimaryTableCell from '../PrimaryTableCell'
import { SpreadsheetDocs } from './StoryHelpers/SpreadsheetTableStoryHelper'

interface ExtendedTData {
  [key: string]: Record<string, unknown>
}

const meta: Meta<typeof Spreadsheet> = {
  title: 'Components/Spreadsheet/Spreadsheet',
  component: Spreadsheet,
  parameters: {
    docs: {
      page: () => <DocsTemplate description={<SpreadsheetDocs />} />,
    },
  },
}
export default meta

type Story = StoryObj<typeof Spreadsheet>

const commonProps = {
  columns: editCellColumns as ColumnDef<ExtendedTData>[],
  noDataFields: {
    primaryText: 'No Data Available',
    secondaryText: 'Please refine your search.',
  },
  customHeight: 500,
  customWidth: 1000,
  subHeaderKeyName: 'amplifi_attr_name',
}

const CellEditingExample = (args: SpreadsheetProps<ExtendedTData>) => {
  const [isOpen, setIsOpen] = useState(false)
  const [isInvalid, setIsInvalid] = useState(false)
  const [selectedRowData, setSelectedRowData] = useState<ExtendedTData>()
  const [originValue, setOriginValue] = useState('')
  const inputRef = useFocus(isOpen)

  const onRowClick = ({
    data,
    selectedCell,
  }: {
    data: ExtendedTData
    selectedCell: string
  }) => {
    if (data?.[selectedCell]?.editable) {
      setIsOpen(true)
      setSelectedRowData(data)
      setOriginValue(String(data[selectedCell]?.value || ''))
    }
  }

  const closeDrawer = () => {
    setIsOpen(false)
    setSelectedRowData({})
    setOriginValue('')
  }

  const submitForm = (close: () => void) => {
    // Here you would typically update your data source
    close()
    closeDrawer()
  }

  return (
    <>
      <SideDrawer
        headerContent='Edit Cell'
        isOpen={isOpen}
        closeCallout={closeDrawer}
        footerContent={({ close }) => (
          <FormFooter
            cancelButtonProps={{
              onClick: close,
            }}
            saveButtonProps={{
              onClick: () => {
                if (!isInvalid) {
                  submitForm(close)
                }
              },
              children: 'Save',
              disabled: isInvalid,
            }}
          />
        )}
      >
        {({ close }) => (
          <>
            <PrimaryTableCell
              sortBy={{ prop: 'product_title', order: 'asc' }}
              title={String(selectedRowData?.product?.product_title || '')}
              titleProp='product_title'
              uniqId={{
                id: String(selectedRowData?.product?.asin || ''),
                idLabel: 'ASIN',
                idName: 'asin',
              }}
              description={String(selectedRowData?.product?.description || '')}
            />

            {isInvalid && (
              <div className='mt-4'>
                <Alert type='error' text='Please enter a valid value' />
              </div>
            )}

            <div className='mt-4'>
              <TextInput
                hasError={isInvalid}
                labelText='Edit Value'
                value={originValue}
                callout={(_, value) => {
                  setOriginValue(String(value))
                  setIsInvalid(!value) // Simple validation example
                }}
                ref={inputRef}
                onReturnCallout={() => {
                  if (!isInvalid) {
                    submitForm(close)
                  }
                }}
              />
            </div>
          </>
        )}
      </SideDrawer>
      <Spreadsheet {...args} onRowClick={onRowClick} />
    </>
  )
}

// Basic configuration
export const Basic: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: editableData as unknown as ExtendedTData[],
  },
}

// Loading state
export const Loading: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    loading: true,
    data: [],
  },
}

// With sticky columns
export const WithStickyColumns: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: exampleSpreadsheetData as unknown as ExtendedTData[],
    stickyTableConfig: {
      left: 2,
      right: 1,
      header: 1,
    },
  },
}

// With row highlighting
export const WithRowHighlighting: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: highlightsRowSpreadsheetData as unknown as ExtendedTData[],
  },
}

// With pagination
export const WithPagination: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: fewSpreadsheetRows as unknown as ExtendedTData[],
    hasMore: true,
  },
}

// Review mode
export const ReviewMode: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: exampleSpreadsheetData as unknown as ExtendedTData[],
    isReviewMode: true,
  },
}

// With last row deletion
export const WithLastRowDeletion: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: exampleSpreadsheetData as unknown as ExtendedTData[],
    isLastRowDeleted: {
      isRowDelete: true,
      tooltipMessage: 'This is the last row',
      confirmButtonText: 'Delete',
    },
  },
}

// With search
export const WithSearch: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: manySpreadsheetRows as unknown as ExtendedTData[],
    searchTerm: 'example',
  },
}

// With custom dimensions
export const WithCustomDimensions: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: exampleSpreadsheetData as unknown as ExtendedTData[],
    customHeight: 300,
    customWidth: 800,
    rowHeight: 50,
  },
}

// With no border
export const WithNoBorder: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: exampleSpreadsheetData as unknown as ExtendedTData[],
    noOutsideBorder: true,
  },
}

// With minimal data
export const MinimalData: Story = {
  render: (args) => <CellEditingExample {...args} />,
  args: {
    ...commonProps,
    data: data as unknown as ExtendedTData[],
  },
}
