import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import Grid from '@mui/material/Grid';
import { Suspense, useMemo, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { paths } from 'src/routes/paths';
import HeadingRekam from 'src/shared/components/HeadingRekam';
import z from 'zod';
import Divider from '@mui/material/Divider';
import FormSkeleton from 'src/shared/skeletons/FormSkeleton';
import Agreement from 'src/shared/components/agreement/Agreement';
import Stack from '@mui/material/Stack';
import PanduanDnRekam from '../components/rekam/PanduanDnRekam';
import { useParams, usePathname } from 'src/routes/hooks';
import Identitas from '../components/rekam/Identitas';
import { checkCurrentPage } from '../utils/utils';
import PerhitunganPPhPasal21 from '../components/rekam/PerhitunganPPhPasal21';
import { KODE_OBJEK_PAJAK, KODE_OBJEK_PAJAK_TEXT } from '../constant';
import JumlahPerhitunganForm from '../components/rekam/JumlahPerhitunganForm';
import { Field } from 'src/components/hook-form';

const bulananSchema = z.object({
  tglPemotongan: z.string().nonempty('Tanggal Pemotongan wajib diisi'),
  thnPajak: z.string().nonempty('Tahun Pajak wajib diisi'),
  msPajak: z.string().nonempty('Masa Pajak wajib diisi'),
  nitku: z
    .string()
    .nonempty('NITKU wajib diisi')
    .regex(/^\d{22}$/, 'NITKU harus 22 digit'),
  namaDipotong: z.string().nonempty('Nama wajib diisi'),
  idDipotong: z
    .string()
    .nonempty('NPWP wajib diisi')
    .regex(/^\d{16}$/, 'NPWP harus 16 digit'),
  email: z.string().optional(),
  noDokLainnya: z.string().nonempty('No Dokumen Lainnya wajib diisi'),
  // bisa tambah field lain sesuai kebutuhan
  keterangan1: z.string().optional(),
  keterangan2: z.string().optional(),
  keterangan3: z.string().optional(),
  keterangan4: z.string().optional(),
  keterangan5: z.string().optional(),
});

export const BulananRekamView = () => {
  const { id } = useParams();
  const pathname = usePathname();

  const [isOpenPanduan, setIsOpenPanduan] = useState<boolean>(false);
  const [isCheckedAgreement, setIsCheckedAgreement] = useState<boolean>(false);

  const actionRekam = checkCurrentPage(pathname);
  const dataListKOP = useMemo(
    () =>
      [KODE_OBJEK_PAJAK.BULANAN_01, KODE_OBJEK_PAJAK.BULANAN_02, KODE_OBJEK_PAJAK.BULANAN_03].map(
        (value) => ({
          value,
          label: `${value} : ${KODE_OBJEK_PAJAK_TEXT[value]}`,
        })
      ),
    []
  );
  type BpuFormData = z.infer<typeof bulananSchema>;

  const handleOpenPanduan = () => setIsOpenPanduan(!isOpenPanduan);

  const defaultValues = {
    tglPemotongan: '',
    thnPajak: '',
    msPajak: '',
    idDipotong: '',
    nitku: '',
    namaDipotong: '',
    email: '',
    keterangan1: '',
    keterangan2: '',
    keterangan3: '',
    keterangan4: '',
    keterangan5: '',
    kdObjPjk: '',
    fgFasilitas: '',
    noDokLainnya: '',
    jmlBruto: 0,
    tarif: '',
    PerhitunganPPhPasal21: '',
    namaDok: '',
    nomorDok: '',
    tglDok: '',
    idTku: '',
  };

  const methods = useForm<BpuFormData>({
    mode: 'all',
    resolver: zodResolver(bulananSchema),
    defaultValues,
  });

  const SubmitRekam = () => {
    console.log('Submit API');
  };
  const MockNitku = [
    {
      nama: '1091031210912281000000',
    },
    {
      nama: '1091031210912281000001',
    },
  ];
  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Add Bupot PPh Pasal 21 Bulanan"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          {
            name: 'e-Bupot PPh Pasal 21 Bulanan',
            href: paths.pph21.bulanan,
          },
          { name: 'Add Bupot PPh Pasal 21 Bulanan' },
        ]}
      />

      <HeadingRekam label="Rekam Bupot PPh Pasal 21 Bulanan" />

      <Grid container columnSpacing={2} /* container otomatis */>
        <Grid size={{ xs: isOpenPanduan ? 8 : 11 }}>
          <form onSubmit={methods.handleSubmit(SubmitRekam)}>
            <FormProvider {...methods}>
              <Suspense fallback={<FormSkeleton />}>
                <Identitas />

                <Suspense fallback={<FormSkeleton />}>
                  <PerhitunganPPhPasal21 kodeObjectPajak={dataListKOP} />
                </Suspense>

                <JumlahPerhitunganForm />

                <Grid size={{ md: 12 }}>
                  <Field.Autocomplete
                    name="idTku"
                    label="NITKU Pemotong"
                    options={MockNitku.map((a) => ({ value: a, label: a }))}
                  />
                </Grid>

                <Divider />

                <Grid size={12}>
                  <Agreement
                    isCheckedAgreement={isCheckedAgreement}
                    setIsCheckedAgreement={setIsCheckedAgreement}
                    text="Dengan ini saya menyatakan bahwa Bukti Pemotongan/Pemungutan Unifikasi telah
                      saya isi dengan benar secara elektronik sesuai
                      dengan"
                  />
                </Grid>

                <Stack direction="row" gap={2} justifyContent="end" marginTop={2}>
                  <LoadingButton
                    type="submit"
                    //   loading={saveDn.isLoading}
                    disabled={!isCheckedAgreement}
                    variant="outlined"
                    sx={{ color: '#143B88' }}
                  >
                    Save as Draft
                  </LoadingButton>
                  <LoadingButton
                    type="button"
                    disabled={!isCheckedAgreement}
                    //   onClick={handleClickUploadSsp}
                    //   loading={uploadDn.isLoading}
                    variant="contained"
                    sx={{ background: '#143B88' }}
                  >
                    Save and Upload
                  </LoadingButton>
                </Stack>
              </Suspense>
            </FormProvider>
          </form>
        </Grid>
        <Grid size={{ xs: isOpenPanduan ? 4 : 1 }}>
          <PanduanDnRekam handleOpen={handleOpenPanduan} isOpen={isOpenPanduan} />
        </Grid>
      </Grid>
    </DashboardContent>
  );
};
