import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

import _ from 'lodash';
import {
  CircleCheckIcon,
  DownloadCloudIcon,
  LoaderCircleIcon,
  ServerCrashIcon,
  Table2Icon,
  Trash2,
  XIcon,
} from 'lucide-react';
import { MdOutlineDownload } from 'react-icons/md';

import { rpc } from '@/api/request';
import { ShmExportType } from '@/api/types';
import {
  Empty,
  EmptyDescription,
  EmptyHeader,
  EmptyMedia,
  EmptyTitle,
} from '@/components/ui/empty';
import {
  Item,
  ItemActions,
  ItemContent,
  ItemDescription,
  ItemMedia,
  ItemTitle,
} from '@/components/ui/item';
import { Lang } from '@/lang/Lang';

import { Button } from '@/components/ui/button';
import { SystemWindowDialog } from '@/components/ui/system-window-dialog';
import {
  MobileButton,
  MobileLink,
  MobileList,
  MobileListItem,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from '@/components/ui/mobile';
import { Skeleton } from '@/components/ui/skeleton';
import useAppConfigStore, { useAppConfig } from '@/stores/appConfig';

export const exportDialogRef = React.createRef<{
  open: () => void;
}>();

const ExportDialog = forwardRef((props, ref) => {
  const [open, setOpen] = useState<boolean>(false);

  useImperativeHandle(
    ref,
    () => {
      return {
        open: () => {
          setOpen(true);
        },
      };
    },
    []
  );

  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<ShmExportType[]>([]);



  const updateInterval = useRef<any>(null);


  useEffect(() => {



    if (open) {

      updateInterval.current = setInterval(() => {

        rpc.listExport().then((res) => {

          setData(res.result ?? []);
        });

      }, 3000);

      setLoading(true);
      rpc.listExport().then((res) => {

        setData(res.result ?? []);
      }).finally(() => {
        setLoading(false);
      });
    }

    return () => {
      if (updateInterval.current) {
        clearInterval(updateInterval.current);
        updateInterval.current = null;
      }
    };

  }, [open]);


  const { color } = useAppConfig();


  const getStatusText = (val: ShmExportType) => {
    switch (val.status) {
      case 'pending':
        return Lang.key("export_data_pending");
      case 'processing':
        return Lang.key("export_data_processing");
      case 'done':
        return Lang.key("export_data_done");
      case 'error':
        return Lang.key("export_data_error");
      default:
        return null;
    }
  }

  const getIcon = (val: ShmExportType) => {

    switch (val.status) {
      case 'pending':
        return <LoaderCircleIcon
          className='animate-spin'
          size={20} />
      case 'processing':
        return <Table2Icon
          className='animate-pulse'
          size={20} />
      case 'done':
        return <CircleCheckIcon
          className='text-green-800'
          size={20} />
      case 'error':
        return <ServerCrashIcon className='text-red-500' size={20} />
      default:
        return null;
    }
  }

  const { isMobile } = useAppConfigStore();

  if (isMobile) {

    return <MobilePopup opened={open} onBackdropClick={() => {
      setOpen(false);
    }}>
      <MobilePage>
        <MobileNavbar
          title={Lang.key('export_data')}
          right={<MobileLink onClick={() => {
            setOpen(false);
          }}><XIcon /></MobileLink>}
        />


        {loading && [1, 2, 3, 4].map(() => {
          return <Skeleton className='w-full h-10' />
        })}

        {!loading && data.length == 0 && <Empty>
          <EmptyHeader>
            <EmptyMedia variant="icon">
              <DownloadCloudIcon />
            </EmptyMedia>
            <EmptyTitle>{Lang.key("no_export_data")}</EmptyTitle>
            <EmptyDescription>
              {Lang.key("no_export_data_description")}
            </EmptyDescription>
          </EmptyHeader>


        </Empty>}

        {!loading && data.length > 0 && <MobileList outline>
          {data.map((val) => (

            <MobileListItem
              media={getIcon(val)}
              title={val.title}
              footer={getStatusText(val)}
              after={<div className='flex gap-2'>
                {val.status == "done" && <MobileButton
                  onClick={() => {


                    window.open(val.fileUrl, '_blank');
                  }}

                >
                  <MdOutlineDownload size={20} />
                </MobileButton>}
                <MobileButton
                  onClick={() => {
                    rpc.deleteExport({
                      _id: val._id,
                    }).then(() => {
                      setData((pre) => pre.filter((v) => v._id != val._id));
                    });
                  }}
                >
                  <Trash2 size={20} />
                </MobileButton>
              </div>}
            >
            </MobileListItem>


          ))}
        </MobileList>}

      </MobilePage>
    </MobilePopup>

  }

  return (
    <SystemWindowDialog
      open={open}
      onOpenChange={() => setOpen(false)}
      title={Lang.key('export_data')}
      width={560}
      height="min(70vh, 640px)"
    >
        {loading && [1, 2, 3, 4].map((i) => (
          <Skeleton key={i} className='w-full h-10' />
        ))}

        {!loading && data.length == 0 && <Empty>
          <EmptyHeader>
            <EmptyMedia variant="icon">
              <DownloadCloudIcon />
            </EmptyMedia>
            <EmptyTitle>{Lang.key("no_export_data")}</EmptyTitle>
            <EmptyDescription>
              {Lang.key("no_export_data_description")}
            </EmptyDescription>
          </EmptyHeader>


        </Empty>}

        {!loading && data.length > 0 && data.map((val) => (
          <Item variant="outline">
            <ItemMedia>
              {getIcon(val)}
            </ItemMedia>
            <ItemContent>
              <ItemTitle>{val.title}</ItemTitle>
              <ItemDescription>
                {getStatusText(val)}
              </ItemDescription>
            </ItemContent>
            <ItemActions>
              <Button
                onClick={() => {
                  window.open(val.fileUrl, '_blank');
                }}

                disabled={val.status != "done"}
                variant="outline" size="sm">
                <MdOutlineDownload size={20} />
              </Button>
              <Button
                onClick={() => {

                  rpc.deleteExport({
                    _id: val._id,
                  }).then(() => {
                    setData((pre) => pre.filter((v) => v._id != val._id));
                  });

                }}


                variant="outline" size="sm">
                <Trash2 size={20} />
              </Button>
            </ItemActions>
          </Item>
        ))}



    </SystemWindowDialog>
  );
});

export default ExportDialog;
