'use client';

import * as React from 'react';
import { useRouter } from 'next/navigation';
import { COL_LESSON_TYPES } from '@/constants';
import { LoadingButton } from '@mui/lab';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Plus as PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';
import type { ListResult, RecordModel } from 'pocketbase';
import PocketBase from 'pocketbase';
import { useTranslation } from 'react-i18next';

import { paths } from '@/paths';
import { logger } from '@/lib/default-logger';
import { pb } from '@/lib/pb';
import { toast } from '@/components/core/toaster';
import type { LessonType } from '@/components/dashboard/lesson_type/ILessonType';
import { emptyLessonType, safeAssignment } from '@/components/dashboard/lesson_type/interfaces';
import { LessonTypesFilters } from '@/components/dashboard/lesson_type/lesson-types-filters';
import type { Filters } from '@/components/dashboard/lesson_type/lesson-types-filters';
import { LessonTypesPagination } from '@/components/dashboard/lesson_type/lesson-types-pagination';
import { LessonTypesSelectionProvider } from '@/components/dashboard/lesson_type/lesson-types-selection-context';
import { LessonTypesTable } from '@/components/dashboard/lesson_type/lesson-types-table';
import FormLoading from '@/components/loading';

// const pb = new PocketBase(process.env.NEXT_PUBLIC_POCKETBASE_URL);

interface PageProps {
  searchParams: {
    email?: string;
    phone?: string;
    sortDir?: 'asc' | 'desc';
    spStatus?: string;
    spName?: string;
    spVisible?: string;
    spType?: string;
    //
  };
}

export default function Page({ searchParams }: PageProps): React.JSX.Element {
  const { t } = useTranslation();
  const { email, phone, sortDir, spStatus, spName, spVisible, spType } = searchParams;
  const router = useRouter();

  const [recordCount, setRecordCount] = React.useState<number>(0);
  const [rowsPerPage, setRowsPerPage] = React.useState<number>(5);
  const [currentPage, setCurrentPage] = React.useState<number>(1);

  //
  const [isLoadingAddPage, setIsLoadingAddPage] = React.useState<boolean>(false);
  const [lessonTypesData, setLessonTypesData] = React.useState<LessonType[]>([]);
  // const [recordModel, setRecordModel] = React.useState<RecordModel[]>([]);
  const sortedLessonTypes = applySort(lessonTypesData, sortDir);
  const filteredLessonTypesOld = applyFilters(sortedLessonTypes, {
    email,
    phone,
    spStatus,
    spName,
    spType,
    spVisible,
    //
  });

  const needToFill = 5 - filteredLessonTypesOld.length;

  const filteredLessonTypes: LessonType[] = filteredLessonTypesOld;
  for (let i = 0; i < needToFill; i++) {
    filteredLessonTypes.push(emptyLessonType);
  }

  const reloadRows = () => {
    pb.collection(COL_LESSON_TYPES)
      .getList(currentPage, rowsPerPage, {})
      .then((lessonTypes: ListResult<RecordModel>) => {
        // console.log(lessonTypes);
        const { items, page, perPage, totalItems, totalPages } = lessonTypes;
        const tempLessonTypes: LessonType[] = items.map((lt) => {
          return safeAssignment(lt);
        });

        setLessonTypesData(tempLessonTypes);
        setRecordCount(totalItems);
      })
      .catch((err) => {
        logger.error(err);
        toast(t('dashboard.lessonTypes.list.error'));
      });

    // pb.collection(COL_LESSON_TYPES)
    //   .getFullList()
    //   .then((lessonTypes: RecordModel[]) => {
    //     const tempLessonTypes: LessonType[] = lessonTypes.map((lt) => {
    //       return safeAssignment(lt);
    //     });
    //     setLessonTypesData(tempLessonTypes);
    //   })
    //   .catch((err) => {
    //     logger.error(err);
    //     toast(t('dashboard.lessonTypes.list.error'));
    //   });
  };

  React.useEffect(() => {
    reloadRows();
  }, []);

  if (lessonTypesData.length < 1) return <FormLoading />;

  return (
    <Box
      sx={{
        maxWidth: 'var(--Content-maxWidth)',
        m: 'var(--Content-margin)',
        p: 'var(--Content-padding)',
        width: 'var(--Content-width)',
      }}
    >
      <Stack spacing={4}>
        <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} sx={{ alignItems: 'flex-start' }}>
          <Box sx={{ flex: '1 1 auto' }}>
            <Typography variant="h4">{t('Lesson Types')}</Typography>
          </Box>
          <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
            <LoadingButton
              loading={isLoadingAddPage}
              onClick={(): void => {
                setIsLoadingAddPage(true);
                router.push(paths.dashboard.lesson_types.create);
              }}
              startIcon={<PlusIcon />}
              variant="contained"
            >
              {/* add new lesson type */}
              {t('dashboard.lessonTypes.add')}
            </LoadingButton>
          </Box>
        </Stack>
        <LessonTypesSelectionProvider lessonTypes={filteredLessonTypes}>
          <Card>
            <LessonTypesFilters
              filters={{ email, phone, spStatus, spName, spVisible, spType }}
              fullData={lessonTypesData}
              sortDir={sortDir}
            />
            <Divider />
            <Box sx={{ overflowX: 'auto' }}>
              <LessonTypesTable reloadRows={reloadRows} rows={filteredLessonTypes} />
            </Box>
            <Divider />
            <LessonTypesPagination
              count={recordCount}
              page={0}
              rowsPerPage={rowsPerPage}
              setRowsPerPage={setRowsPerPage}
              setCurrentPage={setCurrentPage}
            />
          </Card>
        </LessonTypesSelectionProvider>
      </Stack>
    </Box>
  );
}

// Sorting and filtering has to be done on the server.

function applySort(row: LessonType[], sortDir: 'asc' | 'desc' | undefined): LessonType[] {
  return row.sort((a, b) => {
    if (sortDir === 'asc') {
      return a.createdAt.getTime() - b.createdAt.getTime();
    }

    return b.createdAt.getTime() - a.createdAt.getTime();
  });
}

function applyFilters(
  row: LessonType[],
  { email, phone, spStatus: status, spName: name, spVisible: visible }: Filters
): LessonType[] {
  return row.filter((item) => {
    if (email) {
      if (!item.email?.toLowerCase().includes(email.toLowerCase())) {
        return false;
      }
    }

    if (phone) {
      if (!item.phone?.toLowerCase().includes(phone.toLowerCase())) {
        return false;
      }
    }

    if (status) {
      if (item.status !== status) {
        return false;
      }
    }

    if (name) {
      if (!item.name?.toLowerCase().includes(name.toLowerCase())) {
        return false;
      }
    }

    if (visible) {
      if (!item.visible?.toLowerCase().includes(visible.toLowerCase())) {
        return false;
      }
    }

    return true;
  });
}
