// resources\assets\ts\Dash\Card\CardContainer.tsx

import React, { useEffect } from 'react';
import { Trans } from '@lingui/macro';
import CircularProgress from '@mui/material/CircularProgress';
import { DashType } from '../types';
import { TicketItem } from '../requests';
import { useCardContainer } from '../hooks';
import Card, { CardTagFilter } from './Card';
import FormDialog from './FormDialog';
import InfoDialog from './InfoDialog';
import Table from './Table';
import TicketCard from './TicketCard';
import EmptyState from './EmptyState';

import Barchart from './Barchart';
import Linechart from './Linechart';
import Thermometer from './Thermometer';
import BalkenOut from './BalkenList';
import Barchart24 from './Barchart24';
import Linechart24 from './Linechart24';
import IntervallCard from './IntervallCard';
import IntervallZuweisenCard from './IntervallZuweisenCard';
import Kuchen from './Kuchen';

import MapCard from './MapCard';

interface CardContainerProps {
  cardID: number | null;
  refreshTime: number;
  type: DashType; // => 'Map' hier zulassen
  count: number;
  cardContentID: number; // bei 'Map' = Department-ID
  isExternal: boolean;
}

const CardContainer = (props: CardContainerProps) => {
  const { type, cardContentID, refreshTime, isExternal, cardID, count } = props;

  const [
    { isLoading, cardDetails, isFormOpen, isReady, currentItem, isInfoOpen },
    {
      appendForm,
      handleCardClick,
      handleCollectedEventClick,
      handleSave,
      setInfoOpen,
      setIsFormOpen,
      removeItem,
    },
  ] = useCardContainer(cardContentID, refreshTime, type, cardID);

  useEffect(() => {
    const handler = (event: MessageEvent) => {
      if (event.origin !== window.location.origin) return; // security check

      if (event.data?.type === 'FORM_SAVED') {
        removeItem(event.data.payload.id);
      }
    };

    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, [removeItem]);

  if (isLoading) {
    return <CircularProgress />;
  }

  // Keine Daten → standardisierte Meldung (Map ausgenommen, lädt eigene Daten)
  if (type !== 'Map' && Array.isArray(cardDetails) && cardDetails.length === 0) {
    return <EmptyState type={type} count={count} cardContentID={cardContentID} />;
  }

  // Tabellen
  if (type === 'Table') {
    return (
      <>
        <Table serverData={cardDetails} count={count} />
      </>
    );
  }

  // Charts
  if (type === 'Linechart')
    return <Linechart contentId={cardContentID} cardId={cardID} />;
  if (type === 'Barchart')
    return <Barchart contentId={cardContentID} cardId={cardID} />;
  if (type === 'Linechart24')
    return <Linechart24 contentId={cardContentID} cardId={cardID} />;
  if (type === 'Barchart24')
    return <Barchart24 contentId={cardContentID} cardId={cardID} />;

  // Thermometer / Gauge
  if (type === 'Thermometer')
    return <Thermometer contentId={cardContentID} cardId={cardID} />;
  if (type === 'Balken') {
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <BalkenOut contentId={cardContentID} cardId={cardID} />
      </div>
    );
  }

  // Kuchen
  if (
    type === 'Tortendiagramm_Ausstehende_Messungen' ||
    type === 'Tortendiagramm-Aufgaben'
  ) {
    return <Kuchen contentId={cardContentID} cardId={cardID} />;
  }

  // ⬇️ Neu: Map-Card – rendert eine Karte für den ausgewählten Bereich (Department)
  if (type === 'Map') {
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <MapCard departmentId={Number(cardContentID)} />
      </div>
    );
  }

  // Info Karte
  if (type === 'Info') {
    const html = ((cardDetails as any[])?.[0]?.html_info ?? '') as string;
    if (!html.trim()) {
      return <EmptyState type={type} count={count} cardContentID={cardContentID} />;
    }

    return (
      <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '0.5rem' }}>
        <div dangerouslySetInnerHTML={{ __html: html }} />
      </div>
    );
  }

  // Ticket/Intervall-Karten
  let cardView: React.ReactNode = null;

  if (type === 'CollectedEvents') {
    cardView = (cardDetails as unknown as TicketItem[]).map((item) => {
      return (
        <TicketCard
          key={item.ticket_id}
          info={item}
          handleMoreInfoClick={handleCollectedEventClick(item)}
        />
      );
    });
  } else if (type === 'Intervallaufgaben') {
    cardView = (cardDetails as any[]).map((item) => {
      return (
        <IntervallCard
          isExternal={isExternal}
          key={item.ticket_id}
          info={item}
          handleMoreInfoClick={handleCardClick(item)}
        />
      );
    });
  } else if (type === 'Intervallaufgaben_zuweisen') {
    cardView = (cardDetails as any[]).map((item) => (
      <IntervallZuweisenCard
        key={item.agb_id}
        info={item}
      />
    ));
  } else {
    // Default-Cardliste
    cardView = (
      <CardTagFilter cardDetails={(cardDetails as any[]) ?? []}>
        {(filtered) => {
          const list = (filtered as any[]) ?? [];
          let listView: React.ReactNode = list.map((item) => (
            <Card
              isExternal={isExternal}
              info={item}
              handleMoreInfoClick={handleCardClick(item)}
            />
          ));

          if (list.length === 0) {
            listView = (
              <a href={`/config/GRP${cardContentID}`}>
                <Trans>Check config</Trans>
              </a>
            );
          }

          return listView;
        }}
      </CardTagFilter>
    );
  }

  const isShowFormDialog = type === 'CollectedEvents';
  const isFullScreen = isExternal;

  const cardDialogView = isShowFormDialog ? (
    <FormDialog
      appendForm={appendForm}
      open={isFormOpen}
      setIsFormOpen={setIsFormOpen}
      name={currentItem?.name}
      handleSave={handleSave}
      isReady={isReady}
      isFullScreen={isFullScreen}
    />
  ) : (
    <InfoDialog
      open={isInfoOpen}
      close={() => setInfoOpen(false)}
      ergID={currentItem?.ticket_id}
      erglngID={currentItem?.long_id}
      name={currentItem?.name ?? ''}
    />
  );

  return (
    <>
      {cardView}
      {cardDialogView}
    </>
  );
};

export default CardContainer;
