import { useDropzone } from "react-dropzone"
import * as XLSX from "xlsx"
import { useState } from "react"
import { useRsi } from "../../../hooks/useRsi"
import { readFileAsync } from "../utils/readFilesAsync"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import { cn } from "@/lib/utils"

type DropZoneProps = {
  onContinue: (data: XLSX.WorkBook, file: File) => void
  isLoading: boolean
}

export const DropZone = ({ onContinue, isLoading }: DropZoneProps) => {
  const { translations, maxFileSize, dateFormat, parseRaw } = useRsi()
  const [loading, setLoading] = useState(false)
  const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
    noClick: true,
    noKeyboard: true,
    maxFiles: 1,
    maxSize: maxFileSize,
    accept: {
      "application/vnd.ms-excel": [".xls"],
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [".xlsx"],
      "text/csv": [".csv"],
    },
    onDropRejected: (fileRejections) => {
      setLoading(false)
      fileRejections.forEach((fileRejection) => {
        toast.error(`${fileRejection.file.name} ${translations.uploadStep.dropzone.errorToastDescription}`, {
          description: fileRejection.errors[0].message,
        })
      })
    },
    onDropAccepted: async ([file]) => {
      setLoading(true)
      const arrayBuffer = await readFileAsync(file)
      const workbook = XLSX.read(arrayBuffer, {
        cellDates: true,
        dateNF: dateFormat,
        raw: parseRaw,
        dense: true,
        type: 'array',
        codepage: 65001, // UTF-8
        WTF: false // Don't throw on errors
      })
      setLoading(false)
      onContinue(workbook, file)
    },
  })

  return (
    <div
      {...getRootProps()}
      className={cn(
        "flex h-full w-full flex-1 flex-col items-center justify-center rounded-lg border-2 border-dashed border-secondary-foreground/30 bg-muted/90 p-12",
        isDragActive && "border-primary bg-muted"
      )}
    >
      <input {...getInputProps()} data-testid="rsi-dropzone" />
      {isDragActive ? (
        <p className="text-lg text-muted-foreground mb-1 py-6">
          {translations.uploadStep.dropzone.activeDropzoneTitle}
        </p>
      ) : loading || isLoading ? (
        <p className="text-lg text-muted-foreground">
          {translations.uploadStep.dropzone.loadingTitle}
        </p>
      ) : (
        <>
          <p className="mb-4 text-lg text-muted-foreground">
            {translations.uploadStep.dropzone.title}
          </p>
          <Button onClick={open} variant="default">
            {translations.uploadStep.dropzone.buttonTitle}
          </Button>
        </>
      )}
    </div>
  )
}
