import { QrCode2 } from "@mui/icons-material";
import { Button, TextField } from "@mui/material";
import dynamic from "next/dynamic";
import React, { useState } from "react";
import useCameraStore from "../hooks/useCameraStore";

const BarcodeScannerComponent = dynamic(
  () => import("react-qr-barcode-scanner"),
  { ssr: false }
);
const BarcodeScanner: React.FC = () => {
  const { barcode, setBarcode } = useCameraStore();
  const [isCameraActive, setIsCameraActive] = useState(false);

  return (
    <div>
        <Button
          variant="outlined"
          onClick={() => setIsCameraActive(!isCameraActive)}
          startIcon={<QrCode2 />}
          color="error"
          className="mb-2"
        >
          {isCameraActive ? "Cancel" : "Scan Code"}
        </Button>

      {isCameraActive && (
        <BarcodeScannerComponent
          width={500} // Tingkatkan ukuran untuk memperjelas gambar
          height={300}
          onUpdate={(err, result) => {
            if (result) {
              setBarcode(result.getText());
              setIsCameraActive(false);
            }
          }}
        />
      )}

      <div className="mt-4">
        <TextField
          fullWidth
          label="Detected Picking Code"
          id="outlined-basic"
          value={barcode}
          onChange={ (e) => setBarcode(e.target.value) }
          InputLabelProps={{
            shrink: true, // Label akan selalu berada di atas (outline)
          }}
        />
      </div>
    </div>
  );
};

export default BarcodeScanner;
