import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Grid from '@mui/material/Grid';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import { useFormContext } from 'react-hook-form';
import { useParams } from 'react-router';
import { useKodeNegara } from 'src/actions/master-data';
import { Field } from 'src/components/hook-form';

type IdentitasProps = {
  isPengganti?: boolean;
};

const Identitas = ({ isPengganti }: IdentitasProps) => {
  const { dnId } = useParams();
  const { setValue, watch } = useFormContext();
  const tanggalPemotongan = watch('tglPemotongan');
  const fgKaryawanAsing = watch('fgKaryawanAsing');

  const [jumlahKeterangan, setJumlahKeterangan] = useState<number>(0);
  const maxKeterangan = 5;

  const handleTambah = () => {
    if (jumlahKeterangan < maxKeterangan) {
      setJumlahKeterangan(jumlahKeterangan + 1);
    }
  };

  const handleHapus = () => {
    if (jumlahKeterangan > 0) {
      const newCount = jumlahKeterangan - 1;
      setJumlahKeterangan(newCount);
      setValue(`keterangan${newCount + 1}`, null);
    }
  };

  // auto set thnPajak dan msPajak berdasarkan tanggalPemotongan
  useEffect(() => {
    if (tanggalPemotongan) {
      const date = dayjs(tanggalPemotongan);
      setValue('thnPajak', date.format('YYYY'));
      setValue('msPajak', date.format('MM'));
    } else {
      setValue('thnPajak', '');
      setValue('msPajak', '');
    }
  }, [tanggalPemotongan, setValue]);

  const { kodeNegara } = useKodeNegara();

  return (
    <>
      <Grid container rowSpacing={2} alignItems="center" columnSpacing={2} sx={{ mb: 4 }}>
        <Grid size={{ md: 6 }}>
          <Field.DatePicker
            name="tglPemotongan"
            label="Tanggal Pemotongan"
            format="DD/MM/YYYY"
            maxDate={dayjs()}
          />
        </Grid>
        <Grid size={{ md: 3 }}>
          <Field.DatePicker
            name="thnPajak"
            label="Tahun Pajak"
            view="year"
            format="YYYY"
            readOnly
          />
        </Grid>
        <Grid size={{ md: 3 }}>
          <Field.DatePicker name="msPajak" label="Masa Pajak" view="month" format="MM" readOnly />
        </Grid>

        {/* NPWP dengan onChange langsung */}
        <Grid size={{ md: 6 }}>
          <Field.Text
            name="idDipotong"
            label="NPWP"
            onChange={(e) => {
              const value = e.target.value.replace(/\D/g, '').slice(0, 16); // hanya angka, max 16
              console.log('🚀 ~ value:', value);
              setValue('idDipotong', value, { shouldValidate: true, shouldDirty: true });
              setValue('nitku', value.length === 16 ? value + '000000' : value, {
                shouldValidate: true,
                shouldDirty: true,
              });
            }}
          />
        </Grid>
        <Grid size={{ md: 6 }}>
          <Field.Text name="namaDipotong" label="Nama" />
        </Grid>
        <Grid size={{ md: 12 }}>
          <Field.Text name="alamatDipotong" label="Alamat" />
        </Grid>
        <Grid size={{ md: 6 }}>
          <Field.Text name="email" label="Email (optional)" />
        </Grid>
        <Grid size={{ md: 6 }}>
          <Field.Text name="posisiJabatan" label="Jabatan" />
        </Grid>
        <Grid size={{ md: 3 }} alignSelf="center">
          <Field.Checkbox name="fgKaryawanAsing" label="Status Karyawan Asing" />
        </Grid>
        <Grid size={{ md: 3 }}>
          <Field.Autocomplete
            name="kodeNegara"
            label="Negara"
            options={kodeNegara.map((val) => ({ label: val.nama, value: val.kode }))}
            readOnly={!fgKaryawanAsing}
          />
        </Grid>
        <Grid size={{ md: 6 }}>
          <Field.Text
            name="passport"
            label="Paspor"
            slotProps={{
              input: {
                readOnly: !fgKaryawanAsing,
              },
            }}
          />
        </Grid>
      </Grid>

      {/* Tambah / Hapus Keterangan */}
      <Box sx={{ display: 'flex', gap: 2, mb: 3 }}>
        <Box
          sx={{
            borderRadius: '18px',
            border: jumlahKeterangan >= maxKeterangan ? '1px solid #eee' : '1px solid #2e7d3280',
            color: jumlahKeterangan >= maxKeterangan ? '#eee' : '#2e7d3280',
            p: '0px 10px',
          }}
        >
          <Button disabled={jumlahKeterangan >= maxKeterangan} onClick={handleTambah}>
            Tambah Keterangan
          </Button>
        </Box>
        <Box
          sx={{
            borderRadius: '18px',
            border: jumlahKeterangan === 0 ? '1px solid #eee' : '1px solid #f44336',
            color: jumlahKeterangan === 0 ? '#eee' : '#f44336',
            p: '0px 10px',
          }}
        >
          <Button disabled={jumlahKeterangan === 0} onClick={handleHapus}>
            Hapus Keterangan
          </Button>
        </Box>
      </Box>

      <Box sx={{ mb: 3 }}>
        {Array.from({ length: jumlahKeterangan }).map((_, i) => (
          <Grid size={{ md: 12 }} key={i}>
            <Field.Text
              sx={{ mb: 2 }}
              name={`keterangan${i + 1}`}
              label={`Keterangan Tambahan ${i + 1}`}
            />
          </Grid>
        ))}
      </Box>
    </>
  );
};

export default Identitas;
