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

import { XIcon } from 'lucide-react';
import readXlsxFile, { Row } from 'read-excel-file';

import { Lang } from '@/lang/Lang';

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

export const readExcelFileModalRef = React.createRef<ReadExcelFileModalRef>();

type ReadExcelFileModalRefOpenProps = {
  onSelect: (data: Row[]) => void;
};

// Описываем интерфейс методов, доступных через ref
export interface ReadExcelFileModalRef {
  open: (params: ReadExcelFileModalRefOpenProps) => void;
  close: () => void;
}

const ReadExcelFileModal = forwardRef<ReadExcelFileModalRef, {}>((_, ref) => {

  const { isMobile } = useAppConfigStore();

  const [isModalOpen, setIsModalOpen] = useState(false);

  const onSelectRef = React.useRef<((data: Row[]) => void) | null>(null);


  const fileInputRef = React.useRef<HTMLInputElement>(null);


  useImperativeHandle(ref, () => ({
    open: ({ onSelect }: ReadExcelFileModalRefOpenProps) => {
      onSelectRef.current = onSelect;
      setIsModalOpen(true);
    },
    close: () => setIsModalOpen(false),
  }));

  if (isMobile) {
    return <MobilePopup
      opened={isModalOpen}
      onBackdropClick={() => setIsModalOpen(false)}
    >
      <MobilePage>
        <MobileNavbar
          title={Lang.key('import_from_excel')}
          right={<MobileLink onClick={() => setIsModalOpen(false)}><XIcon /></MobileLink>}
        />

        <div className='p-4'>

          <div className='text-sm text-gray-500'>
            <p>{Lang.key('import_from_excel_description_one')}</p>
          </div>

          <MobileButton
            onClick={() => {
              fileInputRef.current?.click();
            }}
            className='mt-4'
          >{Lang.key('select_excel_file')}</MobileButton>
          <input
            type="file"
            accept=".xlsx, .xls"
            style={{ position: 'absolute', top: 0, left: 0, opacity: 0, cursor: 'pointer' }}
            ref={fileInputRef}
            onChange={async (e) => {
              const file = e.target.files?.[0];
              if (file) {
                let data = await readXlsxFile(file);
                if (onSelectRef.current) {
                  onSelectRef.current(data);
                }
                setIsModalOpen(false);
              }
            }}
          />
        </div>
      </MobilePage>
    </MobilePopup>
  }


  return (
    <SystemWindowDialog
      open={isModalOpen}
      onOpenChange={setIsModalOpen}
      title={Lang.key('import_from_excel')}
      width={448}
    >
        <div className='text-sm text-gray-500'>
          <p>{Lang.key('import_from_excel_description_one')}</p>
        </div>

        <Button
          className="mt-4"
          onClick={() => {
            fileInputRef.current?.click();
          }}
        >{Lang.key('select_excel_file')}</Button>
        <input
          type="file"
          ref={fileInputRef}
          accept=".xlsx, .xls"
          style={{ position: 'absolute', top: 0, left: 0, opacity: 0, cursor: 'pointer' }}
          onChange={async (e) => {
            const file = e.target.files?.[0];
            if (file) {
              let data = await readXlsxFile(file);

              data = data.filter((row) => row[0] !== null && row[0] !== undefined && row[0] !== "");

              if (onSelectRef.current) {
                onSelectRef.current(data);
              }
              setIsModalOpen(false);
            }
          }}
        />
    </SystemWindowDialog>
  );
});

export default ReadExcelFileModal;
