'use client';

import * as React from 'react';
import { useRouter } from 'next/navigation';
import { COL_LESSON_CATEGORIES } 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 { 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 ErrorDisplay from '@/components/dashboard/error';
import { defaultLessonCategory } from '@/components/dashboard/lesson_category/_constants';
import { LessonCategoriesFilters } from '@/components/dashboard/lesson_category/lesson-categories-filters';
import type { Filters } from '@/components/dashboard/lesson_category/lesson-categories-filters';
import { LessonCategoriesPagination } from '@/components/dashboard/lesson_category/lesson-categories-pagination';
import { LessonCategoriesSelectionProvider } from '@/components/dashboard/lesson_category/lesson-categories-selection-context';
import { LessonCategoriesTable } from '@/components/dashboard/lesson_category/lesson-categories-table';
import { LessonCategory } from '@/components/dashboard/lesson_category/type';
// import type { LessonCategory } from '@/components/dashboard/lp_categories/type';
import FormLoading from '@/components/loading';

// import { lessonCategoriesSampleData } from './lesson-categories-sample-data';

export default function Page({ searchParams }: PageProps): React.JSX.Element {
  const { t } = useTranslation(['lesson_category']);
  const { email, phone, sortDir, status, name, visible, type } = searchParams;
  const router = useRouter();
  const [lessonCategoriesData, setLessonCategoriesData] = React.useState<LessonCategory[]>([]);
  //

  const [isLoadingAddPage, setIsLoadingAddPage] = React.useState<boolean>(false);
  const [showLoading, setShowLoading] = React.useState<boolean>(true);
  const [showError, setShowError] = React.useState<boolean>(false);
  const [rowsPerPage, setRowsPerPage] = React.useState<number>(5);
  //
  const [f, setF] = React.useState<LessonCategory[]>([]);
  const [currentPage, setCurrentPage] = React.useState<number>(1);
  //
  const [recordCount, setRecordCount] = React.useState<number>(0);

  const sortedLessonCategories = applySort(lessonCategoriesData, sortDir);
  const filteredLessonCategories = applyFilters(sortedLessonCategories, { email, phone, status: status });

  //
  const reloadRows = () => {
    setShowLoading(true);

    pb.collection(COL_LESSON_CATEGORIES)
      .getList(currentPage, rowsPerPage, {})
      .then((lessonCategories: ListResult<RecordModel>) => {
        // console.log(lessonTypes);
        const { items, page, perPage, totalItems, totalPages } = lessonCategories;
        const tempLessonCategories: LessonCategory[] = items.map((item) => {
          return { ...defaultLessonCategory, ...item };
        });

        setLessonCategoriesData(tempLessonCategories);
        setRecordCount(totalItems);
      })
      .catch((err) => {
        logger.error(err);
        toast(t('dashboard.lessonTypes.list.error'));
        setShowError(true);
      })
      .finally(() => {
        setShowLoading(false);
      });
  };

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

  if (showLoading) return <FormLoading />;

  if (showError)
    return (
      <ErrorDisplay
        message={t('error.unable-to-process-request', { ns: 'common' })}
        code="500"
        details={t('error.detailed-error-information', { ns: 'common' })}
      />
    );

  // return <pre>{JSON.stringify(lessonCategoriesData, null, 2)}</pre>;

  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('list.title')}</Typography>
          </Box>
          <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
            <LoadingButton
              loading={isLoadingAddPage}
              onClick={(): void => {
                setIsLoadingAddPage(true);
                router.push(paths.dashboard.lesson_categories.create);
              }}
              startIcon={<PlusIcon />}
              variant="contained"
            >
              {t('list.add')}
            </LoadingButton>
          </Box>
        </Stack>
        <LessonCategoriesSelectionProvider lessonCategories={f}>
          <Card>
            <LessonCategoriesFilters
              filters={{ email, phone, status, name, visible, type }}
              fullData={lessonCategoriesData}
              sortDir={sortDir}
            />
            <Divider />
            <Box sx={{ overflowX: 'auto' }}>
              <LessonCategoriesTable reloadRows={reloadRows} rows={filteredLessonCategories} />
            </Box>
            <Divider />
            <LessonCategoriesPagination count={filteredLessonCategories.length + 100} page={0} />
          </Card>
        </LessonCategoriesSelectionProvider>
      </Stack>
    </Box>
  );
}

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

function applySort(row: LessonCategory[], sortDir: 'asc' | 'desc' | undefined): LessonCategory[] {
  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: LessonCategory[], { email, phone, status }: Filters): LessonCategory[] {
  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;
      }
    }

    return true;
  });
}

interface PageProps {
  searchParams: {
    email?: string;
    phone?: string;
    sortDir?: 'asc' | 'desc';
    status?: string;
    name?: string;
    visible?: string;
    type?: string;
    //
  };
}
