"use client"

import { useRouter } from "next/navigation"
import { zodResolver } from "@hookform/resolvers/zod"
import { Camera, ScanLine } from "lucide-react"
import * as React from "react"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import {
  FormPageHeader,
  FormPanel,
  FormSaveBar,
} from "@/app/dashboard/_components/form"
import { Button } from "@/components/ui/button"
import { FieldError } from "@/components/ui/field"
import { generatePosOcrXml } from "@/components/xml-apis/upload-xml/api/upload-xml.api"
import {
  uploadXmlPosOcrSchema,
  type UploadXmlPosOcrFormValues,
} from "@/components/xml-apis/upload-xml/create/schema"
import { cn } from "@/lib/utils"

const listHref = "/dashboard/xml-apis/upload-xml"
const posOcrListHref = `${listHref}?source=pos-ocr`

export function UploadXmlPosOcrForm() {
  const router = useRouter()
  const [fileName, setFileName] = React.useState("")
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null)
  const inputRef = React.useRef<HTMLInputElement>(null)

  const form = useForm<UploadXmlPosOcrFormValues>({
    resolver: zodResolver(uploadXmlPosOcrSchema),
    defaultValues: { fileName: "" },
  })

  const {
    handleSubmit,
    setValue,
    formState: { errors, isSubmitting },
  } = form

  const onSubmit = handleSubmit(async () => {
    try {
      if (!selectedFile) {
        toast.error("Select a POS file")
        return
      }
      await generatePosOcrXml(selectedFile)
      toast.success("XML generated from POS file")
      router.push(posOcrListHref)
    } catch (error) {
      toast.error(error instanceof Error && error.message ? error.message : "Failed to generate XML")
    }
  })

  return (
    <form onSubmit={(e) => void onSubmit(e)} className="pb-4">
      <FormPageHeader
        backHref={listHref}
        breadcrumb={[
          { label: "XML API" },
          { label: "Upload XML", href: listHref },
          { label: "POS OCR upload" },
        ]}
        titleIcon={<ScanLine className="size-5 text-primary" />}
        title="POS OCR upload"
        description="Generate XML from a POS statement image or PDF via the legacy OCR category."
      />

      <FormPanel title="POS file">
        <div className="space-y-6">
          <div
            className={cn(
              "flex min-h-[220px] flex-col items-center justify-center gap-3 rounded-lg border-2 border-dashed border-muted-foreground/30 bg-muted/20 px-6 py-10",
            )}
          >
            <p className="text-sm text-muted-foreground">Drop files here or</p>
            <input
              ref={inputRef}
              type="file"
              accept="image/*,.pdf"
              className="sr-only"
              onChange={(e) => {
                const file = e.target.files?.[0] ?? null
                const name = file?.name ?? ""
                setFileName(name)
                setSelectedFile(file)
                setValue("fileName", name, { shouldValidate: true })
              }}
            />
            <Button
              type="button"
              className="h-auto flex-col gap-2 px-6 py-4"
              onClick={() => inputRef.current?.click()}
            >
              <Camera className="size-8" />
              Browse POS file
            </Button>
            {fileName ? (
              <p className="text-sm text-muted-foreground">{fileName}</p>
            ) : null}
          </div>
          <FieldError
            errors={
              errors.fileName?.message
                ? [{ message: String(errors.fileName.message) }]
                : undefined
            }
          />
        </div>
      </FormPanel>

      <FormSaveBar
        cancelHref={listHref}
        isSaving={isSubmitting}
        saveLabel="Generate XML"
        onReset={() => {
          form.reset({ fileName: "" })
          setFileName("")
          setSelectedFile(null)
          if (inputRef.current) inputRef.current.value = ""
        }}
      />
    </form>
  )
}
