Untitled

 avatar
unknown
plain_text
5 months ago
18 kB
2
Indexable
"use client";

import MainLayout from "@/components/HOC/layout/MainLayout";
import React, { useEffect, useState } from "react";
import { useRouter, useParams } from "next/navigation";
import Image from "next/image";
import axios from "axios";
import { apiEndpoint } from "@/app/api/config";
import Cookies from "js-cookie";
import CheckboxItem from "@/components/Button/CheckBox";

interface Document {
  id: number;
  business_unit_id: number;
  data: {
    todo: {
      device_installed: boolean;
      license_acquired: boolean;
      sample_recording: boolean;
      register_to_police_station: boolean;
    };
    description: string;
    license_number: string;
    attach?: { url: string }[];
  };
  created_at: string;
  updated_at: string;
  type: string;
  name: string;
  download_url: string | null;
}
export default function CCTVCertificatePage() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [uploadSuccess, setUploadSuccess] = useState(false);
  const [documentsLicense, setDocumentsLicense] = useState<Document[]>([]);
  const [business, setBusiness] = useState<any>(null);
  const [companies, setCompanies] = useState<any[]>([]);
  const [userName, setUserName] = useState<string | null>(null);
  const [mostRecentLicense, setMostRecentLicense] = useState<Document | null>(null);
  const [sampleMonitoringFile, setSampleMonitoringFile] = useState<File | null>(null);
  const [todo, setTodo] = useState<Document['data']['todo']>({
    device_installed: false,
    license_acquired: false,
    sample_recording: false,
    register_to_police_station: false,
  });

  const router = useRouter();
  const { id } = useParams();

  useEffect(() => {
    const fetchBusinessDetails = async () => {
      try {
        const userId = Cookies.get("authUserId");
        const storedUserName = Cookies.get("authUserName");

        if (!userId || !storedUserName) {
          router.push("/login");
          return;
        }

        setUserName(storedUserName);

        const companiesResponse = await axios.get(
          `${apiEndpoint}/api/companies?owner_id=${userId}`
        );
        const fetchedCompanies = companiesResponse.data.data;
        setCompanies(fetchedCompanies);

        const businessResponse = await axios.get(
          `${apiEndpoint}/api/business_units/${id}`
        );
        const fetchedBusinesses = businessResponse.data.data;
        setBusiness(fetchedBusinesses);

        const documentsResponseChamber = await axios.get(
          `${apiEndpoint}/api/business_units/${id}/documents?type=cctv_certificate`
        );
        const fetchedDocumentsChamber = documentsResponseChamber.data.data;
        setDocumentsLicense(fetchedDocumentsChamber);

        if (fetchedDocumentsChamber.length > 0) {
          setMostRecentLicense(fetchedDocumentsChamber[0]);
          if (fetchedDocumentsChamber[0].data && fetchedDocumentsChamber[0].data.todo) {
            setTodo(fetchedDocumentsChamber[0].data.todo);
          }
        }

      } catch (error) {
        setError("Failed to fetch business details.");
        console.error("Error fetching business details:", error);
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchBusinessDetails();
    }
  }, [id, router]);

  const handleView = (idDoc: any) => {
    router.push(`/business/cctv-certificate/${id}/detail/${idDoc}`);
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setSelectedFile(file);
    }
  };

  const handleTodoChange = (key: keyof Document['data']['todo']) => {
    setTodo(prevTodo => ({
      ...prevTodo,
      [key]: !prevTodo[key]
    }));
  };

  
  const handleSampleMonitoringFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setSampleMonitoringFile(file);
    }
  };

  const handleSampleMonitoringUpload = async () => {
    if (!sampleMonitoringFile || !mostRecentLicense) return;

    setUploading(true);
    setUploadError(null);

    const formData = new FormData();
    formData.append('file', sampleMonitoringFile);

    try {
      const response = await axios.post(
        `${apiEndpoint}/api/business_units/${id}/documents/${mostRecentLicense.id}/attach`,
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      );

      setUploadSuccess(true);
      setSampleMonitoringFile(null);

      if (response.data.data) {
        // Update the mostRecentLicense with the new data
        setMostRecentLicense(response.data.data);
        // Update the documentsLicense array
        setDocumentsLicense(prevDocs =>
          prevDocs.map(doc =>
            doc.id === response.data.data.id ? response.data.data : doc
          )
        );
      } else {
        console.warn('No updated document data found in the response');
      }
    } catch (error) {
      setUploadError('Failed to upload sample monitoring file.');
      console.error('Error uploading sample monitoring file:', error);
    } finally {
      setUploading(false);
    }
  };

  const handleUpload = async () => {
    router.push(`/business/cctv-certificate/upload/${id}`);
  };

  const handleRemove = () => {
    const fileInput = document.getElementById(
      "dropzone-file"
    ) as HTMLInputElement;
    if (fileInput) {
      fileInput.value = "";
    }
    setSelectedFile(null);
    setUploadSuccess(false);
    setUploadError(null);
  };

  const getIconForFile = (url: string | null) => {
    if (!url) return "/images/Internet.png";

    const lowerUrl = url.toLowerCase();
    if (lowerUrl.includes(".pdf")) {
      return "/images/PdfImage.png";
    } else if (lowerUrl.includes(".png"), (".jpg"), (".jpeg")) {
      return "/images/Doc.png";
    } else {
      return "/images/Internet.png";
    }
  };

  const getFileNameFromUrl = (url: string) => {
    const parts = url.split('/');
    return parts[parts.length - 1].split('?')[0];
  };

  if (loading) {
    return (
      <MainLayout>
        <div className="flex justify-center items-center min-h-screen">
          <p className="text-blue-500">Loading...</p>
        </div>
      </MainLayout>
    );
  }

  if (error) {
    return (
      <MainLayout>
        <div className="flex justify-center items-center min-h-screen">
          <p className="text-red-500">{error}</p>
        </div>
      </MainLayout>
    );
  }


  return (
    <MainLayout>
      <div className="border-solid bg-white p-8 rounded-xl border-2 relative">
        <h3 className="text-base text-gray-400 mb-2">Latest update</h3>
        <div className="flex">
          <Image
            className="h-20 w-20 rounded-xl bg-white border-solid border-2"
            src="/images/Police.png"
            alt="Company Profile"
            width={200}
            height={200}
          />
          <div className="ml-6 mt-4">
            {mostRecentLicense ? (
              <ul className="space-y-4">
                <div className="flex justify-between space-x-8">
                  <li>
                    <h2 className="text-gray-400 text-sm">License Number</h2>
                    <h2 className="text-gray-700 font-bold text-lg">
                      {mostRecentLicense.data.license_number || "-"}
                    </h2>
                  </li>
                </div>
              </ul>
            ) : (
              <li className="mb-5">
                <h2>-</h2>
              </li>
            )}
          </div>
        </div>
        <h1 className="text-black text-2xl font-bold py-4">
          CCTV Certificate
        </h1>

        {/* <div onClick={handleViewDetail} className="absolute cursor-pointer right-4 top-4 mb-4 flex justify-center items-center w-20 h-8 border-2 border-solid border-gray-400 bg-white rounded-full ">
          <h2 className="text-gray-400 text-xs">Detail</h2>
        </div> */}


        <div className="flex flex-col items-center w-full ">
          <div
            className="flex flex-col items-center justify-center w-full h-20 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50"
            onClick={handleUpload}
          >
            <div className="flex space-x-2 text-center items-center justify-center pt-5 pb-6">
              {selectedFile ? (
                selectedFile ? (
                  <p className="text-lg font-semibold mt-2 text-gray-500">
                    {selectedFile.name}
                  </p>
                ) : (
                  <p className="text-lg font-semibold mt-2 text-gray-500">
                    Unsupported file type
                  </p>
                )
              ) : (
                <>
                  <Image
                    className=" min-w-fit"
                    src="/images/add.png"
                    alt="Upload"
                    width={30}
                    height={30}
                  />
                  <p className="text-xs whitespace-nowrap tracking-wider font-semibold mt-2 text-gray-500">
                    Add Document
                  </p>
                </>
              )}
            </div>
            <input
              id="dropzone-file"
              type="file"
              className="hidden"
              onChange={handleFileChange}
            />
          </div>
          {selectedFile && !uploadSuccess && (
            <>
              <div className="flex justify-center p-2 w-full items-center border border-solid border-gray-200 bg-gray-200 mt-6 rounded-xl">
                <Image
                  className=" h-8 w-8 "
                  src="/images/trash.png"
                  alt="Add Document"
                  width={30}
                  height={30}
                />
                <button
                  onClick={handleRemove}
                  className="p-2 bg-gray-200 text-xs text-gray-500 -"
                  disabled={uploading}
                >
                  Remove Document
                </button>
              </div>

              <button
                onClick={handleUpload}
                className="mt-4 px-4 py-4 w-full bg-blue-500 text-white rounded-xl"
                disabled={uploading}
              >
                {uploading ? "Uploading..." : "Upload File"}
              </button>
            </>
          )}

          {uploadSuccess && !selectedFile && <div></div>}
          {uploadError && <p className="text-red-500 mt-2">{uploadError}</p>}
        </div>
      </div>

      <div className="mt-5">
        <ol className="relative border-gray-500">
          {documentsLicense.length > 0 ? (
            documentsLicense.map((doc, index) => (
              <li key={index} className="mb-5">
                <div
                  onClick={() => handleView(doc.id)}
                  className="border-2 w-full border-solid cursor-pointer bg-white rounded-xl p-2 flex items-center"
                >
                  <Image
                    className="h-12 w-12 rounded-xl border-2 border-gray-200 border-solid m-2"
                    src={getIconForFile(doc.download_url)}
                    alt="File Icon"
                    width={100}
                    height={100}
                  />
                  <div className="flex-grow">
                    <h3 className="font-semibold">{doc.name}</h3>
                    {/* <h3 className="text-xs text-gray-400">
                        Upload: {doc.data.startDate || "Not available"}
                      </h3> */}
                  </div>
                  <div className="ml-auto">
                    <Image
                      className="h-6 w-6"
                      src="/images/IconDetail.png"
                      alt="Detail Icon"
                      width={24}
                      height={24}
                    />
                  </div>
                </div>
              </li>
            ))
          ) : (
            <li className="mb-5">
              <p className="text-gray-500">
                No CCTV Certificate documents available.
              </p>
            </li>
          )}
        </ol>
      </div>

      {mostRecentLicense && (
        <div className="mt-4">
          <h3 className="text-lg font-bold mb-2">To Do List:</h3>
          <ul>
            <CheckboxItem
              label="Device Installed"
              checked={todo.device_installed}
              onChange={() => handleTodoChange('device_installed')}
              id="device_installed"
            />
            <CheckboxItem
              label="License Acquired"
              checked={todo.license_acquired}
              onChange={() => handleTodoChange('license_acquired')}
              id="license_acquired"
            />
            <CheckboxItem
              label="Sample Recording"
              checked={todo.sample_recording}
              onChange={() => handleTodoChange('sample_recording')}
              id="sample_recording"
            />
            <CheckboxItem
              label="Register to Police Station"
              checked={todo.register_to_police_station}
              onChange={() => handleTodoChange('register_to_police_station')}
              id="register_to_police_station"
            />
          </ul>
        </div>
      )}

      <div className="mt-4">
        <h3 className="text-lg font-bold mb-2">Sample Monitoring</h3>
        <div className="flex flex-col items-center w-full">
          <div
            className="flex flex-col items-center justify-center w-full h-20 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50"
            onClick={() => document.getElementById('sample-monitoring-file')?.click()}
          >
            <div className="flex space-x-2 text-center items-center justify-center pt-5 pb-6">
              {sampleMonitoringFile ? (
                <p className="text-lg font-semibold mt-2 text-gray-500">
                  {sampleMonitoringFile.name}
                </p>
              ) : (
                <>
                  <Image
                    className="min-w-fit"
                    src="/images/add.png"
                    alt="Upload"
                    width={30}
                    height={30}
                  />
                  <p className="text-xs whitespace-nowrap tracking-wider font-semibold mt-2 text-gray-500">
                    Add Document
                  </p>
                </>
              )}
            </div>
            <input
              id="sample-monitoring-file"
              type="file"
              className="hidden"
              onChange={handleSampleMonitoringFileChange}
            />
          </div>
          {sampleMonitoringFile && (
            <>
              <div className="flex justify-center p-2 w-full items-center border border-solid border-gray-200 bg-gray-200 mt-6 rounded-xl">
                <Image
                  className="h-8 w-8"
                  src="/images/trash.png"
                  alt="Remove Document"
                  width={30}
                  height={30}
                />
                <button
                  onClick={() => setSampleMonitoringFile(null)}
                  className="p-2 bg-gray-200 text-xs text-gray-500"
                  disabled={uploading}
                >
                  Remove Document
                </button>
              </div>

              <button
                onClick={handleSampleMonitoringUpload}
                className="mt-4 px-4 py-4 w-full bg-blue-500 text-white rounded-xl"
                disabled={uploading}
              >
                {uploading ? "Uploading..." : "Upload File"}
              </button>
            </>
          )}

          {uploadSuccess && !sampleMonitoringFile && (
            <p className="text-green-500 mt-2">File uploaded successfully!</p>
          )}
          {uploadError && <p className="text-red-500 mt-2">{uploadError}</p>}
        </div>
      </div>

      {mostRecentLicense && mostRecentLicense.data.attach && mostRecentLicense.data.attach.length > 0 && (
        <div className="mt-4">

          {mostRecentLicense.data.attach.map((file, index) => (
            <div key={index} className="border-2 w-full border-solid cursor-pointer bg-white rounded-xl p-2 flex items-center mb-2">
              <Image
                className="h-12 w-12 rounded-xl border-2 border-gray-200 border-solid m-2"
                src={getIconForFile(file.url)}
                alt="File Icon"
                width={100}
                height={100}
              />
              <div className="flex-grow">
                <h3 className="font-semibold">Sample Document</h3>
                <h3 className="text-xs text-gray-400">
                  Upload: {new Date(mostRecentLicense.updated_at).toLocaleDateString()}
                </h3>
              </div>
              <div className="ml-auto">
                <a href={file.url} target="_blank" rel="noopener noreferrer">
                  <Image
                    className="h-6 w-6"
                    src="/images/IconDetail.png"
                    alt="View Icon"
                    width={24}
                    height={24}
                  />
                </a>
              </div>
            </div>
          ))}
        </div>
      )}
    </MainLayout>
  );
}
Editor is loading...
Leave a Comment