"use client"

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

import {
  FormPageHeader,
  FormPanel,
  FormSaveBar,
} from "@/app/dashboard/_components/form"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { createAccountXmlUpload } from "@/components/xml-apis/account-xml-upload/api/account-xml-upload.api"
import {
  accountXmlUploadCreateSchema,
  type AccountXmlUploadCreateFormValues,
} from "@/components/xml-apis/account-xml-upload/create/schema"
import { XML_API_BANK_NAME_OPTIONS } from "@/components/xml-apis/shared/bank-name-options"
import { XmlFileDropzone } from "@/components/xml-apis/shared/xml-file-dropzone"
import { validateXmlFiles } from "@/components/xml-apis/shared/xml-upload-validation"
import { SettingsSelect } from "@/components/settings/ui/settings-select"

const listHref = "/dashboard/xml-apis/account-xml-upload"

export function AccountXmlUploadCreateForm() {
  const router = useRouter()
  const [fileName, setFileName] = React.useState<string | null>(null)
  const [selectedFile, setSelectedFile] = React.useState<File | null>(null)
  const [fileError, setFileError] = React.useState<string | null>(null)

  const form = useForm<AccountXmlUploadCreateFormValues>({
    resolver: zodResolver(accountXmlUploadCreateSchema),
    defaultValues: { bankName: "please-select", fileName: "" },
    mode: "onBlur",
  })

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

  const applyFile = (files: File[]) => {
    const validationError = validateXmlFiles(files, { single: true })
    if (validationError) {
      setFileError(validationError)
      setFileName(null)
      setSelectedFile(null)
      setValue("fileName", "", { shouldValidate: true })
      return
    }
    setFileError(null)
    const name = files[0]?.name ?? ""
    setFileName(name)
    setSelectedFile(files[0] ?? null)
    setValue("fileName", name, { shouldValidate: true })
  }

  const onSubmit = handleSubmit(async (values) => {
    try {
      if (!selectedFile) {
        toast.error("Select an XML file")
        return
      }
      await createAccountXmlUpload(values, [selectedFile])
      toast.success("Account XML upload created")
      router.push(listHref)
    } catch {
      toast.error("Failed to save")
    }
  })

  return (
    <form onSubmit={(e) => void onSubmit(e)} className="pb-4">
      <FormPageHeader
        backHref={listHref}
        breadcrumb={[
          { label: "XML API" },
          { label: "Account XML Upload", href: listHref },
          { label: "Create new" },
        ]}
        titleIcon={<Users className="size-5 text-primary" />}
        title="Create new account XML upload"
        description="Select a bank and upload a single account XML file."
      />

      <FormPanel title="Upload details">
        <div className="space-y-6">
          <Field data-invalid={!!errors.bankName} className="max-w-md gap-1.5">
            <FieldLabel className="text-sm font-medium">
              Bank name <span className="text-destructive">*</span>
            </FieldLabel>
            <Controller
              name="bankName"
              control={control}
              render={({ field }) => (
                <SettingsSelect
                  value={field.value}
                  onValueChange={field.onChange}
                  options={XML_API_BANK_NAME_OPTIONS}
                  placeholder="Please select"
                />
              )}
            />
            <FieldError
              errors={
                errors.bankName?.message
                  ? [{ message: String(errors.bankName.message) }]
                  : undefined
              }
            />
          </Field>

          <Field
            data-invalid={!!errors.fileName || !!fileError}
            className="max-w-2xl gap-1.5"
          >
            <FieldLabel className="text-sm font-medium">
              File <span className="text-destructive">*</span>
            </FieldLabel>
            <XmlFileDropzone
              multiple={false}
              browseLabel="Browse XML file"
              onFilesChosen={applyFile}
              onFilesSelected={() => {}}
            />
            {fileName ? (
              <p className="text-sm text-muted-foreground">{fileName}</p>
            ) : null}
            <FieldError
              errors={
                fileError || errors.fileName?.message
                  ? [
                      {
                        message: String(
                          fileError ?? errors.fileName?.message
                        ),
                      },
                    ]
                  : undefined
              }
            />
          </Field>
        </div>
      </FormPanel>

      <FormSaveBar
        cancelHref={listHref}
        isSaving={isSubmitting}
        saveLabel="Save changes"
        onReset={() => {
          form.reset({ bankName: "please-select", fileName: "" })
          setFileName(null)
          setFileError(null)
        }}
      />
    </form>
  )
}
