import { ModalButton } from "@/Components/WithModal";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { useEffect } from "react";
import { deleteCookie } from "@/utils/format";
import CompanyModal from "./Modal/CompanyModal";
import DepartmentModal from "./Modal/DepartmentModal";
import { router } from "@inertiajs/react";

function Index(props) {
  useEffect(() => {
    if (!props.company) {
      document.getElementById('modal_company').click()
    }

    if (!!props.company) {
      const company = props.companies?.find((company) => company.value == props.company.id)
      if (!company) {
        deleteCookie('company_id', {
          onSuccess: () => {
            router.visit('/admin/dashboard')
          }
        })
      }
    }

    if (!!props.department) {
      const department = props.departments?.find((department) => department.value == props.department.id)
      if (!department) {
        deleteCookie('department_id', {
          onSuccess: () => {
            router.visit('/admin/dashboard')
          }
        })
      }
    }

    return () => { }
  }, [])

  return (
    <AuthenticatedLayout title={props.title}>
      <div className="flex flex-wrap items-stretch justify-start gap-4 pt-8 ml-2">
        <ReportCard label={``} icon="fa-building">
          <div className="flex gap-4">
            <div className="">
              <p className="text-sm">Perusahaan Aktif</p>
              <p className="font-semibold text-lg">{props.company?.name ?? '-'}</p>
            </div>
          </div>
          <div className="text-end mt-2">
            <ModalButton id="company" className='btn btn-sm btn-outline mr-2'>
              Ganti Perusahaan
            </ModalButton>
          </div>
        </ReportCard>

        {['user', 'manager', 'director'].includes(props?.auth?.user?.role) && (
          <ReportCard label={``} icon="fa-sitemap">
            <div className="flex gap-4">
              <div className="">
                <p className="text-sm">Departemen Aktif</p>
                <p className="font-semibold text-lg">{props.department?.name ?? '-'}</p>
              </div>
            </div>
            <div className="text-end mt-2">
              <ModalButton id="department" disabled={!props?.company?.id} className='btn btn-sm btn-outline mr-2'>
                Ganti Departemen
              </ModalButton>
            </div>
          </ReportCard>
        )}
      </div>

      <CompanyModal />
      <DepartmentModal />
    </AuthenticatedLayout>
  );
}

const ReportCard = ({ children, label, icon }) => {
  return (
    <div className="border bg-blue-100 shadow-lg border-blue-200 bg-opacity-80 px-4 py-2 rounded-lg flex gap-2 w-full sm:w-max">
      <i className={`fas fa-3x opacity-80 ${icon}`}></i>
      <div className="">
        <p className="opacity-90">{label}</p>
        {children}
      </div>
    </div>
  )
}

export default Index;
