"use client";
import Image from "next/image";
import PackageCamera from "./lib/camera/component/pakageCamera";
import BarcodeScanner from "./lib/camera/component/scannerBarcode";
import SjCamera from "./lib/camera/component/sjCamera";
import useCameraStore from "./lib/camera/hooks/useCameraStore";
import Header from "./lib/camera/component/hedear";
import { Button } from "@mui/material";
import { SaveAsOutlined } from "@mui/icons-material";
import axios from "axios";
import odooApi from "./lib/api/odooApi";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getAuth } from "./lib/api/auth";

export default function Home() {
  const [isLogin, setIsLogin] = useState<boolean>(true);
  const {
    barcode,
    imageSj,
    imagePackage,
    setBarcode,
    setImageSj,
    setImagePackage,
  } = useCameraStore();
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const router = useRouter();

  useEffect(() => {
    const token = getAuth();

    if (!token) {
      router.push("/login");
    } else {
      setIsLogin(true);
    }
  }, [router]);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsLoading(true);

    if (!barcode || !imageSj || !imagePackage) {
      alert("Barcode dan gambar harus tersedia.");
      setIsLoading(false);
      return;
    }

    try {
      const newSjImage = imageSj.replace(/^.*?,/, "");
      const newPackageImage = imagePackage.replace(/^.*?,/, "");
      // const method = 'PUT';

      const data = {
        sj_document: newSjImage, // Kirim base64 lengkap dengan prefix
        paket_document: newPackageImage, // Kirim base64 lengkap dengan prefix
      };

      const response = await odooApi(
        "PUT",
        `/api/v1/stock-picking/${barcode}/documentation`,
        data
      );
      console.log(response);
      if (response.status.code == 200) {
        alert("Berhasil Submit Data");
        setBarcode("");
        setImageSj("");
        setImagePackage("");
        setIsLoading(false);
      }
      return response.data;
    } catch (error: unknown) {
      if (error instanceof Error) {
        console.error("Error mengirim data:", error.message);
      } else if (axios.isAxiosError(error)) {
        console.error("Error:", error.response?.data);
      } else {
        console.error("Unknown error:", error);
      }
      setIsLoading(false);
    }
  };

  return (
    <div className="bg-white h-screen overflow-auto">
      <Header />
      {isLogin && (
        <div className="py-4 px-4 sm:px-96 pt-20">
          <form onSubmit={handleSubmit}>
            <div>
              <BarcodeScanner />
            </div>
            <div className="h-4"></div>

            <div className="flex justify-between">
              <SjCamera />
              <PackageCamera />
            </div>
            <div className="h-2"></div>

            {imageSj && (
              <>
                <label className="block mt-2 text-sm font-medium text-gray-700 text-center">
                  Gambar Foto Surat Jalan
                </label>
                <div className="relative w-full h-[300px] border-2 border-gray-200 p-2 rounded-sm">
                  <Image
                    src={imageSj}
                    alt="Captured"
                    layout="fill"
                    objectFit="cover"
                    unoptimized
                    className="p-2"
                  />
                </div>
              </>
            )}

            <div className="h-2"></div>

            {imagePackage && (
              <>
                <label className="block mt-2 text-sm font-medium text-gray-700 text-center">
                  Gambar Foto Penerima
                </label>
                <div className="relative w-full h-[300px] border-2 border-gray-200 p-2 rounded-sm">
                  <Image
                    src={imagePackage}
                    alt="Captured"
                    layout="fill"
                    objectFit="cover"
                    unoptimized
                    className="p-2"
                  />
                </div>
              </>
            )}
            <div>
              <div className="h-4"></div>
              <Button
                className="w-[50%] sm:w-[25%]"
                variant="contained"
                color="error"
                startIcon={<SaveAsOutlined />}
                type="submit"
                disabled={isLoading}
              >
                Simpan
              </Button>
            </div>
          </form>
        </div>
      )}
      {!isLogin && (
        <div className="py-4 px-4 sm:px-96 pt-20">
          <div className="text-center">
            <p className="text-2xl font-bold">Loading...</p>
          </div>
        </div>
      )}
    </div>
  );
}
