import { useCallback, useState, useMemo } from "react"
import type XLSX from "xlsx"
import * as XLSXLib from "xlsx"
import { useRsi } from "../../hooks/useRsi"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { ChevronLeft } from "lucide-react"
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"

type SelectSheetProps = {
  sheetNames: string[]
  workbook: XLSX.WorkBook
  onContinue: (sheetName: string) => Promise<void>
  onBack?: () => void
}

const MAX_PREVIEW_ROWS = 10
const MAX_PREVIEW_COLS = 8
const MAX_CELL_LENGTH = 30

export const SelectSheetStep = ({ sheetNames, workbook, onContinue, onBack }: SelectSheetProps) => {
  const [isLoading, setIsLoading] = useState(false)
  const { translations } = useRsi()
  const [value, setValue] = useState(sheetNames[0])

  // Generate preview data for each sheet
  const sheetPreviews = useMemo(() => {
    const previews: Record<string, (string | number | null)[][]> = {}

    for (const sheetName of sheetNames) {
      const sheet = workbook.Sheets[sheetName]
      if (!sheet) continue

      // Convert sheet to array of arrays
      const data = XLSXLib.utils.sheet_to_json<(string | number | null)[]>(sheet, {
        header: 1,
        defval: null,
      })

      // Take first N rows and limit columns
      const previewRows = data.slice(0, MAX_PREVIEW_ROWS).map(row =>
        (row as (string | number | null)[]).slice(0, MAX_PREVIEW_COLS)
      )

      previews[sheetName] = previewRows
    }

    return previews
  }, [sheetNames, workbook])

  const truncateCell = (value: string | number | null): string => {
    if (value === null || value === undefined) return ""
    const str = String(value)
    if (str.length > MAX_CELL_LENGTH) {
      return str.slice(0, MAX_CELL_LENGTH - 1) + "…"
    }
    return str
  }

  const handleOnContinue = useCallback(
    async (data: typeof value) => {
      setIsLoading(true)
      await onContinue(data)
      setIsLoading(false)
    },
    [onContinue],
  )

  return (
    <div className="flex h-[calc(100vh-10rem)] flex-col">
      <div className="flex-1 overflow-hidden">
        <div className="px-8 py-6">
          <div className="mb-8">
            <h2 className="text-3xl font-semibold text-foreground">
              {translations.uploadStep.selectSheet.title}
            </h2>
          </div>
          <RadioGroup
            value={value}
            onValueChange={setValue}
            className="space-y-6"
          >
            {sheetNames.map((sheetName) => {
              const preview = sheetPreviews[sheetName] || []
              const isSelected = value === sheetName

              return (
                <div
                  key={sheetName}
                  className={`rounded-lg border p-4 transition-colors cursor-pointer ${
                    isSelected ? "border-primary bg-primary/5" : "border-border hover:border-muted-foreground/50"
                  }`}
                  onClick={() => setValue(sheetName)}
                >
                  <div className="flex items-center space-x-2 mb-3">
                    <RadioGroupItem value={sheetName} id={sheetName} />
                    <Label
                      htmlFor={sheetName}
                      className="text-base font-medium cursor-pointer"
                    >
                      {sheetName}
                    </Label>
                    <span className="text-xs text-muted-foreground">
                      ({preview.length === 10 ? 'first ' : ''}{preview.length} rows shown)
                    </span>
                  </div>

                  {preview.length > 0 && (
                    <ScrollArea className="w-full">
                      <div className="rounded border bg-muted/30">
                        <table className="text-xs w-full">
                          <tbody>
                            {preview.map((row, rowIndex) => (
                              <tr
                                key={rowIndex}
                                className={rowIndex === 0 ? "bg-muted/50 font-medium" : ""}
                              >
                                {row.map((cell, colIndex) => (
                                  <td
                                    key={colIndex}
                                    className="px-2 py-1 border-r border-b last:border-r-0 whitespace-nowrap max-w-[150px] overflow-hidden text-ellipsis"
                                    title={cell !== null ? String(cell) : ""}
                                  >
                                    {truncateCell(cell)}
                                  </td>
                                ))}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      <ScrollBar orientation="horizontal" />
                    </ScrollArea>
                  )}

                  {preview.length === 0 && (
                    <p className="text-xs text-muted-foreground italic">
                      No data in this sheet
                    </p>
                  )}
                </div>
              )
            })}
          </RadioGroup>
        </div>
      </div>
      <div className="flex items-center justify-between border-t px-8 py-4 bg-muted -mb-1">
        {onBack && (
          <Button
            variant="ghost"
            onClick={onBack}
            className="gap-2"
          >
            <ChevronLeft className="h-4 w-4" />
            {translations.uploadStep.selectSheet.backButtonTitle}
          </Button>
        )}
        <div className="flex-1" />
        <Button
          onClick={() => handleOnContinue(value)}
          disabled={isLoading}
        >
          {translations.uploadStep.selectSheet.nextButtonTitle}
        </Button>
      </div>
    </div>
  )
}
