import { SignatureAndTeeterService } from "@/record-management/services/api/signatureAndTeeterService";
import { Button } from "@/shared/common/ui/button";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import SignatureForm from "./signatureForm";

const SignatureFormTrigger = ({
  setSignatureUrl,
  employeeId,
  getFileName,
  queryClient,
  setUploadStatus,
}: {
  setSignatureUrl: (url: string) => void;
  employeeId: string;
  getFileName: (type: "signature") => string;
  queryClient: ReturnType<typeof useQueryClient>;
  setUploadStatus: (msg: string) => void;
}) => {
  const [open, setOpen] = useState(false);
  const [isUploading, setIsUploading] = useState(false);

  // helper: base64 -> Blob
  const dataURLtoBlob = (dataUrl: string): Blob => {
    const arr = dataUrl.split(",");
    const mime = arr[0].match(/:(.*?);/)?.[1] || "image/png";
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) u8arr[n] = bstr.charCodeAt(n);
    return new Blob([u8arr], { type: mime });
  };

  const handleSave = async (dataUrl: string) => {
    setIsUploading(true);
    setUploadStatus("Uploading signature...");

    try {
      const blob = dataURLtoBlob(dataUrl);
      const file = new File([blob], getFileName("signature"), {
        type: "image/png",
      });

      await SignatureAndTeeterService.signature.uploadAndCreate(
        file,
        getFileName("signature"),
        employeeId,
      );

      queryClient.invalidateQueries({
        queryKey: ["signatureListWithPresigned"],
      });

      setSignatureUrl(dataUrl); // update local preview
      setUploadStatus("Signature uploaded successfully ✅");
      setOpen(false);
    } catch (err) {
      console.error("Signature upload failed", err);
      setUploadStatus("Signature upload failed ❌");
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="space-y-3">
      {!open ? (
        <Button
          onClick={() => setOpen(true)}
          className="bg-blue-600 text-white w-full hover:bg-blue-700">
          Open Signature Form
        </Button>
      ) : (
        <div className="space-y-3">
          <SignatureForm
            onSubmit={handleSave}
            onCancel={() => setOpen(false)}
          />
          {isUploading && <p className="text-sm text-gray-500">Uploading...</p>}
        </div>
      )}
    </div>
  );
};

export default SignatureFormTrigger;
