import React, { useMemo, useState } from 'react';
import { Dialog, DialogContent } from '../components';
import { MonitorType, Sidebar } from './components/Sidebar';
import { AddItem } from './components/AddItem';
import { useAppDispatch, useInsights } from '..';
import { StartScreen } from './components/StartScreen';
import { FormReport } from './FormReport';
import { FormAlert } from './FormAlert';
import { wsDeleteInsight } from '../data-access/broker/wsInsightSharing';
import { deleteInsight } from '../data-access/store/insightSharingSlice';

type Props = {
  open: boolean;
  onClose: () => void;
};

export function InsightDialog(props: Props) {
  const dispatch = useAppDispatch();

  const [adding, setAdding] = useState<false | MonitorType>(false);
  const [active, setActive] = useState<string>('');
  const insights = useInsights();

  const selectedInsight = useMemo(() => insights.find((i) => i.id === active), [active, insights]);

  const handleDelete = () => {
    if (!selectedInsight) return;

    dispatch(deleteInsight({ id: selectedInsight.id }));
    wsDeleteInsight(selectedInsight.id);
    setActive('');
  };

  return (
    <Dialog
      open={props.open}
      onOpenChange={(ret) => {
        if (!ret) props.onClose();
      }}
    >
      <DialogContent className="w-5/6 h-5/6 rounded-none py-0 px-0">
        <div className="flex w-full h-full">
          <div className="w-1/4 border-r overflow-auto flex flex-col h-full">
            <Sidebar setAdding={setAdding} setActive={setActive} />
          </div>

          <div className="w-3/4 p-8">
            {adding ? (
              <AddItem setAdding={setAdding} setActive={setActive} type={adding} />
            ) : !selectedInsight ? (
              <StartScreen setAdding={setAdding} />
            ) : selectedInsight.type === 'report' ? (
              <FormReport insight={selectedInsight} setActive={setActive} handleDelete={handleDelete} />
            ) : (
              <FormAlert insight={selectedInsight} setActive={setActive} handleDelete={handleDelete} />
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}