import { isNil, set } from 'lodash-es';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { EditableDescription } from '../components/EditableDescription';
import { EditableTitle } from '../components/EditableTitle';
import { Tab } from '../components/Tab';
import { SchemeView } from '../page-components/scheme/SchemeView';
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 [showScheme, setShowScheme] = useState<'light' | 'dark'>('light');

  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],
  );

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

  return (
    <div className={styles.scheme_detail_layout}>
      <EditableTitle title={scheme?.name} onChange={updateTitle} />
      <EditableDescription content={scheme?.description} onChange={updateDescription} />
      <Tab
        tabs={[
          { title: 'Light Scheme', id: 'light' },
          { title: 'Dark Scheme', id: 'dark' },
        ]}
        onActive={(tabId) => setShowScheme(tabId as 'light' | 'dark')}
      />
      <SchemeView scheme={scheme?.[`${showScheme}Scheme`]} />
    </div>
  );
}
