import React, { useRef, useState } from "react"
import * as pdfjsLib from "pdfjs-dist"
import mammoth from "mammoth"
import { SVGS } from "../assets/svgs"
import pdfWorker from "pdfjs-dist/build/pdf.worker?worker"
import { ContentCard } from "./ContentCard"
import useStore from "../utils/store"

pdfjsLib.GlobalWorkerOptions.workerPort = new pdfWorker()

const allowedTypes = [
  "application/pdf",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "text/plain",
  "text/markdown",
]

export interface ParsedFile {
  name: string
  text: string
}

interface FileUploaderProps {
  // onResult: (files: ParsedFile[]) => void
  styledAs?: "button" | "card"
}

const FileUploader: React.FC<FileUploaderProps> = ({ styledAs = "button" }) => {
  const inputRef = useRef<HTMLInputElement>(null)
  const uploadedFiles = useStore((state) => state.uploadedFiles)
  const setUploadedFiles = useStore((state) => state.setUploadedFiles)
  const [isDragging, setIsDragging] = useState(false)
  // const [parsedFiles, setParsedFiles] = useState<ParsedFile[]>([]) F

  const extractText = async (file: File): Promise<ParsedFile> => {
    const { type, name } = file

    if (type === "application/pdf") {
      const arrayBuffer = await file.arrayBuffer()
      const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise
      let text = ""

      for (let i = 0; i < pdf.numPages; i++) {
        const page = await pdf.getPage(i + 1)
        const content = await page.getTextContent()
        text += content.items.map((item: any) => item.str).join(" ") + "\n"
      }

      return { name, text }
    }

    if (
      type ===
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    ) {
      const arrayBuffer = await file.arrayBuffer()
      const { value } = await mammoth.extractRawText({ arrayBuffer })
      return { name, text: value }
    }

    const text = await file.text()
    return { name, text }
  }

  const parseFiles = async (files: FileList | File[]) => {
    const validFiles = Array.from(files).filter((file) =>
      allowedTypes.includes(file.type)
    )
    const parsed = await Promise.all(validFiles.map(extractText))
    setUploadedFiles([...uploadedFiles, ...parsed])
  }

  const handleInput = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files) return
    await parseFiles(e.target.files)
  }

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault()
    setIsDragging(false)
    if (e.dataTransfer.files.length > 0) {
      parseFiles(e.dataTransfer.files)
    }
  }

  return (
    <div className="flex flex-col gap-2 w-full">
      {uploadedFiles.length > 0 && styledAs === "card" && (
        <div className="w-full flex flex-row gap-2 flex-wrap justify-center items-center  ">
          {uploadedFiles.map((file, idx) => (
            <div
              key={idx}
              className="p-3 rounded-md bg-white shadow-sm text-sm text-gray-800 text-left "
              title={file.name}
            >
              <strong>{file.name.slice(0, 20)}...</strong>
              <button
                className="text-gray-600 mt-1 float-right  cursor-pointer"
                onClick={() =>
                  setUploadedFiles(uploadedFiles.filter((_, i) => i !== idx))
                }
              >
                {SVGS.trash}
              </button>
            </div>
          ))}
        </div>
      )}
      {styledAs === "button" && (
        <div className="flex items-center justify-end gap-2 w-100">
          <button
            type="button"
            className="cursor-pointer blue-on-hover flex items-center justify-center w-6 h-6"
            onClick={() => inputRef.current?.click()}
          >
            {SVGS.clip}
          </button>
        </div>
      )}

      {styledAs === "card" && (
        <>
          <ContentCard
            description={
              isDragging
                ? "Drop it here"
                : "Upload a PDF or DOCX file or drag it here"
            }
            icon={isDragging ? SVGS.clip : SVGS.pdf}
            onClick={() => inputRef.current?.click()}
            onDragOver={(e) => {
              e.preventDefault()
              setIsDragging(true)
            }}
            onDragLeave={() => setIsDragging(false)}
            onDrop={handleDrop}
            className={isDragging ? "border-blue-600 bg-blue-50" : ""}
          />
        </>
      )}

      <input
        ref={inputRef}
        type="file"
        multiple
        accept=".pdf,.docx,.txt,.md"
        onChange={handleInput}
        style={{ display: "none" }}
      />
    </div>
  )
}

export default FileUploader
