"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 DispatchCamera from "./lib/camera/component/dispatchCamera";
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";

type AuthLike = { email?: string; token?: string } | string | null;

const DRIVER_EMAILS = new Set(
  ["driverindoteknik@gmail.com", "it@fixcomart.co.id", "sulistianaridwan8@gmail.com"].map(
    (e) => e.toLowerCase()
  )
);
const DISPATCH_EMAILS = new Set(
  ["rahmat.afiudin@gmail.com", "it@fixcomart.co.id"].map((e) => e.toLowerCase())
);

function extractEmailFromAuth(auth: AuthLike): string | null {
  // object with email
  if (auth && typeof auth === "object" && "email" in auth && typeof auth.email === "string") {
    return auth.email;
  }
  // object with token (JWT)
  if (auth && typeof auth === "object" && "token" in auth && typeof auth.token === "string") {
    const t = auth.token;
    const parts = t.split(".");
    if (parts.length === 3) {
      try {
        const payload = JSON.parse(atob(parts[1]));
        const email: unknown =
          payload?.email ?? payload?.preferred_username ?? payload?.sub ?? null;
        return typeof email === "string" ? email : null;
      } catch {
        return null;
      }
    }
  }
  // JWT string
  if (typeof auth === "string") {
    const parts = auth.split(".");
    if (parts.length === 3) {
      try {
        const payload = JSON.parse(atob(parts[1]));
        const email: unknown =
          payload?.email ?? payload?.preferred_username ?? payload?.sub ?? null;
        return typeof email === "string" ? email : null;
      } catch {
        return null;
      }
    }
  }
  return null;
}

export default function Home() {
  const [isLogin, setIsLogin] = useState<boolean>(true);
  const [isDriver, setIsDriver] = useState<boolean>(false);
  const [isDispatch, setIsDispatch] = useState<boolean>(false);

  const {
    barcode,
    imageSj,
    imagePackage,
    imageDispatch,
    setBarcode,
    setImageSj,
    setImagePackage,
    setImageDispatch,
  } = useCameraStore();

  const [isLoading, setIsLoading] = useState<boolean>(false);
  const router = useRouter();

  useEffect(() => {
    const token = getAuth() as AuthLike;
    if (!token) {
      router.push("/login");
    } else {
      setIsLogin(true);
      const email = extractEmailFromAuth(token);
      const lower = (email ?? "").toLowerCase();
      const dispatchFlag = DISPATCH_EMAILS.has(lower);
      const driverFlag = DRIVER_EMAILS.has(lower) && !dispatchFlag;
      setIsDispatch(dispatchFlag);
      setIsDriver(driverFlag);
    }
  }, [router]);

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

    const needDispatch = isDispatch;
    const needDriver = isDriver;

    if (!barcode || !imageSj || (!imagePackage && needDriver)) {
      alert("Barcode, Foto SJ, dan Foto Penerima harus tersedia.");
      setIsLoading(false);
      return;
    }

    if (!barcode || (!imageDispatch && needDispatch)) {
      alert("Foto Dispatch Wajib Diisi");
      setIsLoading(false);
      return;
    }

    try {
      // const newSjImage = imageSj.replace(/^.*?,/, "");
      // const newPackageImage = imagePackage.replace(/^.*?,/, "");
      // const newDispatchImage =
      //   imageDispatch && imageDispatch.startsWith("data:")
      //     ? imageDispatch.replace(/^.*?,/, "")
      //     : undefined;
      const newSjImage = imageSj ? imageSj.replace(/^.*?,/, "") : undefined;
      const newPackageImage = imagePackage ? imagePackage.replace(/^.*?,/, "") : undefined;
      const newDispatchImage =
        imageDispatch && imageDispatch.startsWith("data:")
          ? imageDispatch.replace(/^.*?,/, "")
          : undefined;

      const data: Record<string, string> = {};
      if (newSjImage) data.sj_document = newSjImage;
      if (newPackageImage) data.paket_document = newPackageImage;
      if (!isDriver && newDispatchImage) data.dispatch_document = newDispatchImage;

      const response = (await odooApi(
        "PUT",
        `/api/v1/stock-picking/${barcode}/documentation`,
        data
      )) as { status: { code: number } };

      if (response?.status?.code === 200) {
        alert("Berhasil Submit Data");
        setBarcode("");
        setImageSj("");
        setImagePackage("");
        setImageDispatch("");
      } else if (response?.status?.code === 404) {
        alert("Gagal Submit Data, Picking Code Tidak Ditemukan ");
      } else {
        alert("Gagal Submit Data, Silahkan Coba Lagi");
      }
    } catch (error) {
      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);
      }
    } finally {
      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 className="flex justify-between">
              <SjCamera />
              <PackageCamera />
              {!isDriver && <DispatchCamera />}
            </div>
            <div className="h-2" />

            {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"
                    fill
                    unoptimized
                    className="p-2"
                    style={{ objectFit: "cover" }}
                  />
                </div>
              </>
            )}

            <div className="h-2" />

            {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"
                    fill
                    unoptimized
                    className="p-2"
                    style={{ objectFit: "cover" }}
                  />
                </div>
              </>
            )}

            <div className="h-2" />

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

            <div className="h-4" />
            <Button
              className="w-[50%] sm:w-[25%]"
              variant="contained"
              color="error"
              startIcon={<SaveAsOutlined />}
              type="submit"
              disabled={isLoading}
            >
              Simpan
            </Button>
          </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>
  );
}
