'use client';

import * as React from 'react';
import GetAllCount from '@/db/LessonTypes/GetAllCount.tsx';
import { ListChecks as ListChecksIcon } from '@phosphor-icons/react/dist/ssr/ListChecks';
import { useTranslation } from 'react-i18next';

import { Summary } from '@/components/dashboard/overview/summary';
import { LoadingSummary } from '@/components/dashboard/overview/summary/LoadingSummary';

function LessonTypeCount(): React.JSX.Element {
  const { t } = useTranslation();
  const [amount, setAmount] = React.useState<number>(0);
  const [isLoading, setIsLoading] = React.useState<boolean>(true);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const count = await GetAllCount();
        setAmount(count);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setIsLoading(false);
      }
    };

    void fetchData();
  }, []);

  if (isLoading) {
    return (
      <LoadingSummary
        diff={15}
        icon={ListChecksIcon}
        title={t('課程類型')}
        trend="up"
      />
    );
  }

  if (error) {
    return (
      <Summary
        amount={0}
        diff={0}
        icon={ListChecksIcon}
        title={t('Error')}
        trend="down"
      />
    );
  }

  return (
    <Summary
      amount={amount}
      diff={15}
      icon={ListChecksIcon}
      title={t('課程類型')}
      trend="up"
    />
  );
}

export default React.memo(LessonTypeCount);
