import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import Grid from '@mui/material/Grid';
import { useState, useEffect } 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 Identitas from '../components/rekamNr/Identitas';
import Divider from '@mui/material/Divider';
import FormSkeleton from 'src/shared/skeletons/FormSkeleton';
import PphDipotong from '../components/rekamNr/PphDipotong';
import useGetKodeObjekPajak from '../hooks/useGetKodeObjekPajakNr';
import DokumenReferensi from '../components/rekamNr/DokumenReferensi';
import Agreement from 'src/shared/components/agreement/Agreement';
import Stack from '@mui/material/Stack';
import PanduanNrRekam from '../components/rekamNr/PanduanNrRekam';
import useSaveNr from '../hooks/useSaveNr';
import { enqueueSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router';
import useUpload from '../hooks/useUpload';
import ModalUploadNr from '../components/dialog/ModalUploadNr';
import { useGetNrById } from '../hooks/useGetNr';
import useGetNegara from '../hooks/useGetNegara';

const bpuNrSchema = z
  .object({
    tglPemotongan: z.string().nonempty('Tanggal Pemotongan harus diisi'),
    thnPajak: z.string().nonempty('Tahun Pajak harus diisi'),
    masaPajak: z.string().nonempty('Masa Pajak harus diisi'),
    idDipotong: z.string().nonempty('TIN harus diisi'),
    alamatDipotong: z.string().nonempty('Alamat harus diisi'),
    namaDipotong: z.string().nonempty('Nama harus diisi'),
    negaraDipotong: z.string().nonempty('Negara harus diisi'),
    tmptLahirDipotong: z.string().nonempty('Tempat Lahir harus diisi'),
    tglLahirDipotong: z.string().nonempty('Tanggal Lahir harus diisi'),
    nomorPaspor: z.string().nonempty('No Paspor harus diisi'),
    nomorKitasKitap: z.string().nonempty('No.KITAS/KITAP harus diisi'),
    keterangan1: z.string().optional(),
    keterangan2: z.string().optional(),
    keterangan3: z.string().optional(),
    keterangan4: z.string().optional(),
    keterangan5: z.string().optional(),
    kodeObjekPajak: z.string().nonempty('Kode Objek Pajak harus diisi'),
    fgFasilitas: z.string().nonempty('Fasilitas harus diisi'),
    noDokLainnya: z.string().optional(),
    penghasilanBruto: z.string().nonempty('Jumlah Penghasilan Bruto harus diisi'),
    normaPenghasilanNeto: z.string().nonempty('Perkiraan Penghasilan Netto (%) harus diisi'),
    tarif: z.union([z.string().nonempty('Tarif harus diisi'), z.number()]),
    pphDipotong: z.string().nonempty('PPh Yang Dipotong/Dipungut harus diisi'),
    namaDok: z.string().nonempty('Nama Dokumen harus diisi'),
    nomorDok: z.string().nonempty('Nomor Dokumen harus diisi'),
    tglDok: z.string().nonempty('Tanggal Dokumen harus diisi'),
    idTku: z.string().nonempty('Cabang harus diisi'),
  })
  .superRefine((data, ctx) => {
    // Field dianggap DISABLED kalau fgFasilitas kosong ('') atau '9'
    const isDisabled = ['', '9'].includes(data.fgFasilitas);

    // Jika tidak disabled, berarti aktif → wajib isi
    if (!isDisabled && (!data.noDokLainnya || data.noDokLainnya.trim() === '')) {
      ctx.addIssue({
        path: ['noDokLainnya'],
        code: 'custom',
        message: 'No Dokumen Lainnya harus diisi',
      });
    }
  });

const NrRekamView = () => {
  const { id, type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();

  const [isOpenPanduan, setIsOpenPanduan] = useState<boolean>(false);
  const [isCheckedAgreement, setIsCheckedAgreement] = useState<boolean>(false);
  const [isFormPrefilled, setIsFormPrefilled] = useState<boolean>(false);
  const [formInitialized, setFormInitialized] = useState<boolean>(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState<boolean>(false);

  const isEdit = type === 'ubah';
  const isPengganti = type === 'pengganti';

  const { data: existingNr, isLoading: isLoadingDn } = useGetNrById(id!, {
    enabled: !!id && (isEdit || isPengganti),
  });

  const { data: country = [] } = useGetNegara();

  const { data: kodeObjekPajak, isLoading: isLoadingKop } = useGetKodeObjekPajak();
  const navigate = useNavigate();

  type BpuNrFormData = z.infer<typeof bpuNrSchema>;

  const saveNr = useSaveNr({
    onSuccess: () => enqueueSnackbar('Data berhasil disimpan', { variant: 'success' }),
  });

  const uploadNr = useUpload();

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

  const defaultValues: BpuNrFormData = {
    tglPemotongan: '',
    thnPajak: '',
    masaPajak: '',
    idDipotong: '',
    namaDipotong: '',
    alamatDipotong: '', // ✅ disamakan
    negaraDipotong: '', // ✅ disamakan
    tmptLahirDipotong: '', // ✅ disamakan
    tglLahirDipotong: '',
    nomorPaspor: '', // ✅ disamakan
    nomorKitasKitap: '', // ✅ disamakan
    keterangan1: '',
    keterangan2: '',
    keterangan3: '',
    keterangan4: '',
    keterangan5: '',
    kodeObjekPajak: '', // ✅ disamakan
    fgFasilitas: '',
    noDokLainnya: '',
    penghasilanBruto: '',
    normaPenghasilanNeto: '', // ✅ disamakan
    tarif: '',
    pphDipotong: '',
    namaDok: '',
    nomorDok: '',
    tglDok: '',
    idTku: '',
  };

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

  const { reset, handleSubmit } = methods;

  useEffect(() => {
    if (isEdit || isPengganti) {
      if (existingNr && !isLoadingKop) {
        // 🧩 Normalisasi nilai numeric ke string sebelum reset
        const normalized = {
          ...existingNr,
          jmlBruto:
            existingNr.penghasilanBruto !== null && existingNr.penghasilanBruto !== undefined
              ? String(existingNr.penghasilanBruto)
              : '',
          tarif:
            existingNr.tarif !== null && existingNr.tarif !== undefined
              ? String(existingNr.tarif)
              : '',
          pphDipotong:
            existingNr.pphDipotong !== null && existingNr.pphDipotong !== undefined
              ? String(existingNr.pphDipotong)
              : '',
          masaPajak:
            existingNr.msPajak !== null && existingNr.msPajak !== undefined
              ? String(existingNr.msPajak)
              : '',
          namaDok: existingNr.namaDok ?? '',
          nomorDok: existingNr.nomorDok ?? '',
          tglDok: existingNr.tglDok ?? '',
        };

        reset(normalized);
        setIsFormPrefilled(true);
        setFormInitialized(true);
      }
    } else {
      setIsFormPrefilled(false);
      setFormInitialized(true);
    }
  }, [existingNr, isLoadingKop, isEdit, isPengganti, reset]);

  const buildPayload = (values: BpuNrFormData) => {
    if (isEdit) {
      return {
        ...values,
        id,
        isPengganti: false,
      };
    }

    if (isPengganti) {
      return {
        ...values,
        id,
        isPengganti: true,
        idBupot: existingNr?.idBupot,
        noBupot: existingNr?.noBupot,
        revNo: existingNr?.revNo ?? 0,
      };
    }

    return {
      ...values,
      isPengganti: false,
    };
  };

  const onSubmit = async (values: BpuNrFormData) => {
    console.log('ini ke klik');
    try {
      const payload = buildPayload(values);

      await saveNr.mutateAsync(payload);

      enqueueSnackbar(
        isEdit
          ? 'Data berhasil diperbarui'
          : isPengganti
            ? 'Data pengganti berhasil disimpan'
            : 'Data berhasil disimpan',
        { variant: 'success' }
      );

      navigate('/unifikasi/nr');
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Gagal menyimpan data', { variant: 'error' });
      console.error('❌ saveNr error:', error);
    }
  };

  const handleSaveAndUpload = async (values: BpuNrFormData) => {
    try {
      const payload = buildPayload(values);
      const res: any = await saveNr.mutateAsync(payload);

      const savedId = res?.[0]?.id;
      if (!savedId) throw new Error('ID dokumen tidak ditemukan dari hasil save');

      await uploadNr.mutateAsync({ id: savedId });

      enqueueSnackbar('Data berhasil disimpan dan diupload', { variant: 'success' });
      navigate('/unifikasi/nr');
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Gagal save & upload data', { variant: 'error' });
      console.error('❌ Upload error:', error);
    }
  };

  if (isLoadingDn || isLoadingKop || !formInitialized) {
    return (
      <DashboardContent>
        <CustomBreadcrumbs
          heading={
            isEdit
              ? 'Ubah Bupot Unifikasi'
              : isPengganti
                ? 'Bupot Pengganti'
                : 'Tambah Bupot Unifikasi'
          }
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'e-Bupot Non Residen', href: paths.unifikasi.nr },
            { name: isEdit ? 'Ubah' : isPengganti ? 'Pengganti' : 'Tambah' },
          ]}
        />

        <HeadingRekam
          label={
            isEdit
              ? 'Ubah Data Bukti Pemotongan/Pemungutan PPh Non Residen'
              : isPengganti
                ? 'Rekam Bukti Pengganti PPh Non Residen'
                : 'Rekam Data Bukti Potong PPh Non Residen'
          }
        />
        <FormSkeleton numberOfRows={8} />
      </DashboardContent>
    );
  }

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading={
          isEdit
            ? 'Ubah Bupot Non Residen'
            : isPengganti
              ? 'Bupot Non Residen Pengganti'
              : 'Tambah Bupot Non Residen'
        }
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'e-Bupot Non Residen', href: paths.unifikasi.nr },
          { name: isEdit ? 'Ubah' : isPengganti ? 'Pengganti' : 'Tambah' },
        ]}
      />

      <HeadingRekam
        label={
          isEdit
            ? 'Ubah Data Bukti Pemotongan/Pemungutan PPh Non Residen'
            : isPengganti
              ? 'Rekam Bukti Pengganti PPh Non Residen'
              : 'Rekam Data Bukti Potong PPh Non Residen'
        }
      />

      <Grid container columnSpacing={2}>
        <Grid size={{ xs: isOpenPanduan ? 8 : 11 }}>
          <FormProvider {...methods}>
            <form onSubmit={handleSubmit(onSubmit)}>
              <Identitas isPengganti={isPengganti} existingNr={existingNr} country={country} />
              <Divider />
              <PphDipotong
                kodeObjectPajak={kodeObjekPajak?.data ?? []}
                isFormPrefilled={isFormPrefilled}
              />
              <DokumenReferensi />
              <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={saveNr.isPending}
                  disabled={!isCheckedAgreement}
                  variant="outlined"
                  sx={{ color: '#143B88' }}
                >
                  Save as Draft
                </LoadingButton> */}
                <LoadingButton
                  type="button"
                  loading={saveNr.isPending}
                  disabled={!isCheckedAgreement}
                  variant="outlined"
                  sx={{ color: '#143B88' }}
                  onClick={() => {
                    console.log('🟢 Save as Draft clicked');
                    methods.handleSubmit(
                      async (values) => {
                        console.log('✅ Form valid, calling onSubmit...');
                        await onSubmit(values);
                      },
                      (errors) => {
                        console.error('❌ Validation errors:', errors);
                      }
                    )();
                  }}
                >
                  Save as Draft
                </LoadingButton>
                <LoadingButton
                  type="button"
                  disabled={!isCheckedAgreement}
                  //   onClick={() => methods.handleSubmit(handleSaveAndUpload)()}
                  onClick={() => setIsUploadModalOpen(true)}
                  loading={uploadNr.isPending}
                  variant="contained"
                  sx={{ background: '#143B88' }}
                >
                  Save and Upload
                </LoadingButton>
              </Stack>
            </form>
          </FormProvider>
        </Grid>
        <Grid size={{ xs: isOpenPanduan ? 4 : 1 }}>
          <PanduanNrRekam handleOpen={handleOpenPanduan} isOpen={isOpenPanduan} />
        </Grid>
      </Grid>

      {isUploadModalOpen && (
        <ModalUploadNr
          isOpenDialogUpload={isUploadModalOpen}
          setIsOpenDialogUpload={setIsUploadModalOpen}
          onConfirmUpload={() => handleSaveAndUpload(methods.getValues())}
          singleUploadPayload={methods.getValues()}
        />
      )}
    </DashboardContent>
  );
};

export default NrRekamView;
