import dayjs from 'dayjs';
import { isNil, set } from 'lodash-es';
import { useCallback, useEffect, useMemo } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { EditableDescription } from '../components/EditableDescription';
import { EditableTitle } from '../components/EditableTitle';
import { SchemeSign } from '../components/SchemeSign';
import { CorruptedScheme } from '../page-components/scheme/CorruptedScheme';
import { M2Scheme } from '../page-components/scheme/M2Scheme';
import { M3Scheme } from '../page-components/scheme/M3Scheme';
import { QScheme } from '../page-components/scheme/QScheme';
import { SwatchScheme } from '../page-components/scheme/SwatchScheme';
import { useScheme, useUpdateScheme } from '../stores/schemes';
import styles from './SchemeDetail.module.css';

export function SchemeDetail() {
  const { id } = useParams();
  const scheme = useScheme(id);
  const navigate = useNavigate();
  const updateScheme = useUpdateScheme(id);

  const updateTitle = useCallback(
    (newTitle: string) => {
      updateScheme((prev) => {
        set(prev, 'name', newTitle);
        return prev;
      });
    },
    [id],
  );
  const updateDescription = useCallback(
    (newDescription: string | null) => {
      updateScheme((prev) => {
        set(prev, 'description', newDescription);
        return prev;
      });
    },
    [id],
  );
  const schemeContent = useMemo(() => {
    switch (scheme?.type) {
      case 'q_scheme':
        return <QScheme scheme={scheme} />;
      case 'swatch_scheme':
        return <SwatchScheme scheme={scheme} />;
      case 'material_2':
        return <M2Scheme scheme={scheme} />;
      case 'material_3':
        return <M3Scheme scheme={scheme} />;
      default:
        return <CorruptedScheme />;
    }
  }, [scheme]);

  useEffect(() => {
    if (isNil(scheme)) {
      navigate('../not-found');
    }
  }, [scheme, navigate]);

  return (
    <div className={styles.scheme_detail_layout}>
      <EditableTitle title={scheme?.name} onChange={updateTitle} />
      <div className={styles.badge_layout}>
        <SchemeSign scheme={scheme?.type} />
        <div className={styles.create_time}>
          created at {dayjs(scheme?.createdAt).format('YYYY-MM-DD')}
        </div>
      </div>
      <EditableDescription content={scheme?.description} onChange={updateDescription} />
      {schemeContent}
    </div>
  );
}
