"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,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  FormHelperText,
  IconButton,
  Tooltip,
} from "@mui/material";
import { SaveAsOutlined, Close as CloseIcon } 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";
import { getCookie } from "cookies-next";
import { clearOdooSession } from "./lib/api/clearOdooSession";

type Role = "driver" | "dispatch";
type ShipMethod = "" | "self_pickup" | "indoteknik_delivery" | "ekspedisi";

export default function Home() {
  const [isLogin, setIsLogin] = useState<boolean>(false);
  const [isDriver, setIsDriver] = useState<boolean>(false);
  const [isDispatch, setIsDispatch] = useState<boolean>(false);
  const [shippingMethod, setShippingMethod] = useState<ShipMethod>("");
  const [shipTouched, setShipTouched] = useState(false);

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

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

  // Auth gate + role dari cookie
  useEffect(() => {
    const auth = getAuth();
    if (!auth) {
      void clearOdooSession(process.env.NEXT_PUBLIC_ODOO_API_HOST ?? "");
      router.replace("/login");
      return;
    }
    const roleCookie = (
      getCookie("web_role") as string | undefined
    )?.toLowerCase() as Role | undefined;
    setIsDriver(roleCookie === "driver");
    setIsDispatch(roleCookie === "dispatch");
    setIsLogin(true);
  }, [router]);

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

    if (!barcode) {
      alert("Barcode harus diisi.");
      setIsLoading(false);
      return;
    }

    if (isDispatch) setShipTouched(true);
    if (isDispatch && !shippingMethod) {
      alert("Shipping Method wajib dipilih.");
      setIsLoading(false);
      return;
    }

    const sjArr: string[] = Array.isArray(imageSj)
      ? imageSj
      : imageSj
      ? [imageSj as unknown as string]
      : [];

    if (isDispatch) {
      if (!imageDispatch) {
        alert("Foto Dispatch Wajib Diisi");
        setIsLoading(false);
        return;
      }
    } else {
      if (sjArr.length < 1 || !imagePackage) {
        alert("Barcode, Foto SJ, dan Foto Penerima harus tersedia.");
        setIsLoading(false);
        return;
      }
    }

    try {
      const latestSj = sjArr.at(-1) || null;
      const newSjImage = latestSj ? latestSj.replace(/^.*?,/, "") : undefined;

      const newPackageImage = imagePackage
        ? imagePackage.replace(/^.*?,/, "")
        : undefined;

      const newDispatchImage =
        imageDispatch && imageDispatch.startsWith("data:")
          ? imageDispatch.replace(/^.*?,/, "")
          : imageDispatch || undefined;

      // Kirim hanya yang ada
      const submittedSj = !!newSjImage;
      const submittedPackage = !!newPackageImage;
      const submittedDispatch = !!newDispatchImage && !isDriver;

      const data: Record<string, string> = {};
      if (submittedSj) data.sj_documentations = newSjImage; // plural sesuai API
      if (submittedPackage) data.paket_document = newPackageImage!;
      if (submittedDispatch) data.dispatch_document = newDispatchImage!;
      if (isDispatch && shippingMethod) data.shipping_method = shippingMethod;
      if (shippingMethod === "self_pickup") data.self_pu = "true";

      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("");

        if (submittedSj) {
          const next = sjArr.slice(0, -1);
          setImageSj(next);
        }
        if (submittedPackage) setImagePackage("");
        if (submittedDispatch) 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 (axios.isAxiosError(error)) {
        console.error("Error:", error.response?.data);
      } else if (error instanceof Error) {
        console.error("Error mengirim data:", error.message);
      } else {
        console.error("Unknown error:", error);
      }
    } finally {
      setIsLoading(false);
    }
  };

  // === UI helpers ===
  const sjArr: string[] = Array.isArray(imageSj)
    ? imageSj
    : imageSj
    ? [imageSj as unknown as string]
    : [];

  // dispatch: SJ hanya utk self_pickup & ekspedisi
  const showSjForDispatch =
    isDispatch &&
    (shippingMethod === "self_pickup" || shippingMethod === "ekspedisi");
  const showDispatchForDispatch = isDispatch && shippingMethod !== "";

  const showSjPreview = sjArr.length > 0 && (!isDispatch || showSjForDispatch);
  const showDispatchPreview =
    !!imageDispatch && (!isDispatch || showDispatchForDispatch);

  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>

            {/* Shipping Method (khusus dispatch) */}
            {isDispatch && (
              <div className="mt-4">
                <FormControl
                  fullWidth
                  size="small"
                  required
                  error={shipTouched && !shippingMethod}
                >
                  <InputLabel id="shipping-label" shrink>
                    Shipping Method
                  </InputLabel>
                  <Select
                    labelId="shipping-label"
                    id="shipping"
                    label="Shipping Method"
                    value={shippingMethod}
                    displayEmpty
                    onChange={(e) =>
                      setShippingMethod(e.target.value as ShipMethod)
                    }
                    onBlur={() => setShipTouched(true)}
                    renderValue={(selected) => {
                      if (!selected)
                        return (
                          <span style={{ opacity: 0.6 }}>
                            Pilih Shipping Method
                          </span>
                        );
                      const map: Record<string, string> = {
                        self_pickup: "Self Pickup",
                        indoteknik_delivery: "Indoteknik Delivery",
                        ekspedisi: "Ekspedisi",
                      };
                      return map[selected as string] ?? "";
                    }}
                  >
                    <MenuItem value="">
                      <em>Pilih Shipping Method</em>
                    </MenuItem>
                    <MenuItem value="self_pickup">Self Pickup</MenuItem>
                    <MenuItem value="indoteknik_delivery">
                      Indoteknik Delivery
                    </MenuItem>
                    <MenuItem value="ekspedisi">Ekspedisi</MenuItem>
                  </Select>
                  {shipTouched && !shippingMethod && (
                    <FormHelperText>
                      Wajib pilih shipping method.
                    </FormHelperText>
                  )}
                </FormControl>
              </div>
            )}

            <div className="h-4" />

            <div className="flex justify-between gap-3">
              {isDispatch ? (
                <>
                  {showSjForDispatch && <SjCamera />}
                  {showDispatchForDispatch && <DispatchCamera />}
                </>
              ) : (
                <>
                  {/* driver / non-dispatch */}
                  <SjCamera />
                  <PackageCamera />
                </>
              )}
            </div>

            <div className="h-2" />

            {/* Preview SJ (multi) + Remove per item */}
            {showSjPreview && (
              <>
                <label className="block mt-2 text-sm font-medium text-gray-700 text-center">
                  Gambar Foto Surat Jalan
                </label>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                  {sjArr.map((src, i) => (
                    <div
                      key={i}
                      className="relative w-full h-[180px] border-2 border-gray-200 rounded-sm"
                    >
                      <Image
                        src={src}
                        alt={`SJ ${i + 1}`}
                        fill
                        unoptimized
                        style={{ objectFit: "cover" }}
                        className="rounded-sm"
                      />
                      <div className="absolute top-1 right-1">
                        <Tooltip title="Remove">
                          <IconButton
                            size="small"
                            onClick={() => removeSjImage(i)}
                            sx={{
                              bgcolor: "rgba(255,255,255,0.85)",
                              "&:hover": { bgcolor: "rgba(255,255,255,1)" },
                            }}
                          >
                            <CloseIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}

            {/* Preview Penerima (hanya non-dispatch) */}
            {!isDispatch && imagePackage && (
              <>
                <label className="block mt-4 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>
              </>
            )}

            {/* Preview Dispatch */}
            {showDispatchPreview && (
              <>
                <label className="block mt-4 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>
      ) : (
        <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>
  );
}
