import { appApi } from 'src/boot/axios';
import { ref, computed } from 'vue';
import type { Member, Members } from 'src/vueLib/models/member';
import { useNotify } from 'src/vueLib/general/useNotify';
import { i18n } from 'boot/lang';

export const databaseName = ref('members.dba');

export function useMemberTable() {
  const members = ref<Members>([]);

  const pagination = ref({
    sortBy: 'firstName',
    descending: false,
    page: 1,
    rowsPerPage: 10,
  });

  const columns = computed(() => [
    { name: 'cake', align: 'center' as const, label: '', field: 'cake', icon: 'cake' },
    {
      name: 'firstName',
      align: 'left' as const,
      label: i18n.global.t('prename'),
      field: 'firstName',
      sortable: true,
    },
    {
      name: 'lastName',
      align: 'left' as const,
      label: i18n.global.t('lastName'),
      field: 'lastName',
      sortable: true,
    },
    {
      name: 'birthday',
      align: 'left' as const,
      label: i18n.global.t('birthday'),
      field: 'birthday',
      sortable: true,
    },
    {
      name: 'age',
      align: 'left' as const,
      label: i18n.global.t('age'),
      field: 'age',
      sortable: true,
    },
    {
      name: 'address',
      align: 'left' as const,
      label: i18n.global.t('address'),
      field: 'address',
      sortable: true,
    },
    {
      name: 'town',
      align: 'left' as const,
      label: i18n.global.t('town'),
      field: 'town',
      sortable: true,
    },
    {
      name: 'zip',
      align: 'left' as const,
      label: i18n.global.t('zipCode'),
      field: 'zip',
      sortable: true,
    },
    {
      name: 'phone',
      align: 'left' as const,
      label: i18n.global.t('phone'),
      field: 'phone',
      sortable: true,
    },
    {
      name: 'email',
      align: 'left' as const,
      label: i18n.global.t('email'),
      field: 'email',
      sortable: true,
    },
    {
      name: 'group',
      align: 'left' as const,
      label: i18n.global.t('group'),
      field: 'group',
      sortable: true,
    },
    {
      name: 'responsiblePerson',
      align: 'left' as const,
      label: i18n.global.t('responsible'),
      field: 'responsiblePerson',
      sortable: true,
    },
    {
      name: 'firstVisit',
      align: 'left' as const,
      label: i18n.global.t('firstVisit'),
      field: 'firstVisit',
      sortable: true,
    },
    {
      name: 'lastVisit',
      align: 'left' as const,
      label: i18n.global.t('lastVisit'),
      field: 'lastVisit',
      sortable: true,
    },
    { name: 'option', align: 'center' as const, label: '', field: 'option', icon: 'option' },
  ]);

  const { NotifyResponse } = useNotify();

  const loading = ref(false);

  function calculateAge(birthDateString: string) {
    if (birthDateString === undefined) return 0;
    const [day, month, year] = birthDateString.split('.').map(Number); // for format "1.2.2000"
    if (year === undefined || month === undefined || day === undefined) return 0;
    const birthDate = new Date(year, month - 1, day); // month is 0-based

    const today = new Date();

    let age = today.getFullYear() - birthDate.getFullYear();

    // Check if birthday has occurred yet this year
    const hasBirthdayPassed =
      today.getMonth() > birthDate.getMonth() ||
      (today.getMonth() === birthDate.getMonth() && today.getDate() >= birthDate.getDate());

    if (!hasBirthdayPassed) {
      age--;
    }

    return age;
  }

  //isThreeDaysBeforeAnnualDate check if upcoming date is less than 3 days from now
  function isXDaysBeforeAnnualDate(dateString: string, before: number) {
    if (dateString === undefined) return;
    const [day, month] = dateString.split('.').map(Number);

    const today = new Date();
    today.setHours(0, 0, 0);

    const annualDate = new Date(today.getFullYear(), month ? month - 1 : 0, day);
    annualDate.setHours(0, 0, 1);

    const xDaysBefore = new Date(annualDate);
    xDaysBefore.setDate(annualDate.getDate() - before);

    return today >= xDaysBefore && today <= annualDate;
  }

  function getRowClass(row: Member) {
    if (isXDaysBeforeAnnualDate(row.birthday, 1)) {
      return 'bg-red-2 text-red-10';
    } else if (isXDaysBeforeAnnualDate(row.birthday, 4)) {
      return 'bg-green-2 text-green-10';
    } else if (isXDaysBeforeAnnualDate(row.birthday, 8)) {
      return 'bg-amber-2 text-amber-10';
    }
    return '';
  }

  //updates member list from database
  function updateMembers() {
    loading.value = true;

    appApi
      .get('secure/members')
      .then((resp) => {
        if (resp.data === null) {
          members.value = [];
          return;
        }
        members.value = resp.data as Members;
        if (members.value === null) {
          members.value = [];
          return;
        }
        members.value.forEach((member) => {
          if (member.birthday !== undefined) {
            member.age = String(calculateAge(member.birthday));
          }
        });
      })

      .catch((err) => {
        NotifyResponse(err, 'error');
      })
      .finally(() => {
        loading.value = false;
      });
  }

  return {
    members,
    pagination,
    columns,
    loading,
    getRowClass,
    updateMembers,
    isXDaysBeforeAnnualDate,
  };
}
