"use client"

import { toastApiError } from "@/lib/toast-api-error";
import Link from "next/link"
import { Archive, FileText, Loader2, X } from "lucide-react"
import * as React from "react"
import { toast } from "sonner"

import {
  FormPageHeader,
  FormPanel,
} from "@/app/dashboard/_components/form"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { submitNomuraBulkTxtToXml } from "@/components/xml-apis/bank-api/api/bank-api.api"

const listHref = "/dashboard/xml-apis/bank-api"

type BankApiNomuraBulkTxtToXmlFormProps = {
  bankId: string
  bankName: string
  onShowSingleView: () => void
}

export function BankApiNomuraBulkTxtToXmlForm({
  bankId,
  bankName,
  onShowSingleView,
}: BankApiNomuraBulkTxtToXmlFormProps) {
  const [files, setFiles] = React.useState<File[]>([])
  const [fileError, setFileError] = React.useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = React.useState(false)

  const handleFilesChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const nextFiles = Array.from(event.target.files ?? [])
    setFiles(nextFiles)
    setFileError(null)
  }

  const handleReset = () => {
    setFiles([])
    setFileError(null)
  }

  const handleSubmit = async () => {
    if (!files.length) {
      setFileError("Select at least one TXT file")
      return
    }

    setIsSubmitting(true)
    try {
      await submitNomuraBulkTxtToXml({ bankId, bankName, files })
      toast.success("Merged POS + TRX ZIP downloaded")
    } catch (error) {
      toastApiError(error, "Failed to download merged ZIP")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="pb-4">
      <FormPageHeader
        backHref={listHref}
        breadcrumb={[
          { label: "XML API" },
          { label: "Bank Api", href: listHref },
          { label: "TXT To XML" },
        ]}
        titleIcon={<Archive className="size-5 text-primary" />}
        title="Bulk TXT → merged POS + TRX (ZIP)"
        description={`${bankName} — Upload many TXT files and download one merged ZIP.`}
        meta={
          <div className="flex flex-wrap items-center gap-2">
            <Button type="button" variant="outline" size="sm" className="gap-1.5" onClick={onShowSingleView}>
              <FileText className="size-4" />
              Single-type TXT to XML
            </Button>
            <Button type="button" variant="outline" size="sm" className="gap-1.5" asChild>
              <Link href={listHref}>
                <X className="size-4" />
                Cancel
              </Link>
            </Button>
          </div>
        }
      />

      <div className="space-y-6">
        <Alert className="border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100">
          <AlertDescription>
            Upload many <code className="rounded bg-sky-100 px-1 py-0.5 text-xs dark:bg-sky-900">.txt</code> files at
            once. Each file is routed to <strong>position</strong> or <strong>transaction</strong> output from its name:
            Include <code className="rounded bg-sky-100 px-1 py-0.5 text-xs dark:bg-sky-900">pos</code> /{" "}
            <code className="rounded bg-sky-100 px-1 py-0.5 text-xs dark:bg-sky-900">position</code> for POS, or{" "}
            <code className="rounded bg-sky-100 px-1 py-0.5 text-xs dark:bg-sky-900">trx</code> /{" "}
            <code className="rounded bg-sky-100 px-1 py-0.5 text-xs dark:bg-sky-900">transaction</code> for TRX.
          </AlertDescription>
        </Alert>

        <FormPanel title={`Upload TXT Files ${bankId}`}>
          <Field data-invalid={!!fileError} className="gap-2">
            <FieldLabel htmlFor={`nomura-bulk-txt-${bankId}`} className="text-sm font-medium">
              TXT files (multiple)
            </FieldLabel>
            <Input
              id={`nomura-bulk-txt-${bankId}`}
              type="file"
              accept=".txt,text/plain"
              multiple
              className="h-9 cursor-pointer file:mr-3 file:rounded-md file:border-0 file:bg-muted file:px-3 file:py-1 file:text-xs file:font-medium"
              onChange={handleFilesChange}
            />
            <p className="text-xs text-muted-foreground">
              Select all .txt files in one go (Ctrl/Cmd+click for multiple).
            </p>
            {files.length > 0 ? (
              <ul className="text-sm text-muted-foreground">
                {files.map((file) => (
                  <li key={`${file.name}-${file.lastModified}`}>{file.name}</li>
                ))}
              </ul>
            ) : null}
            <FieldError errors={fileError ? [{ message: fileError }] : undefined} />
          </Field>
        </FormPanel>
      </div>

      <div className="sticky bottom-0 z-10 -mx-4 mt-6 flex flex-wrap items-center justify-end gap-2 border-t bg-background/95 px-4 py-3 backdrop-blur supports-[backdrop-filter]:bg-background/80 md:-mx-6 md:px-6">
        <Button type="button" variant="ghost" size="sm" onClick={handleReset} disabled={isSubmitting}>
          Reset
        </Button>
        <Button
          type="button"
          size="sm"
          className="min-w-[280px] gap-1.5"
          disabled={isSubmitting}
          onClick={() => void handleSubmit()}
        >
          {isSubmitting ? (
            <>
              <Loader2 className="size-4 animate-spin" />
              Preparing ZIP…
            </>
          ) : (
            <>
              <Archive className="size-4" />
              Download ZIP (merged POS + TRX XML)
            </>
          )}
        </Button>
      </div>
    </div>
  )
}
