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

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

import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

import { Button } from './ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from './ui/dialog';
import {
  MobileButton,
  MobileLink,
  MobileNavbar,
  MobilePage,
  MobilePopup,
} from './ui/mobile';

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 } = useAppConfig();

  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 (
    <Dialog


      open={isModalOpen}

      onOpenChange={(open) => setIsModalOpen(open)}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{Lang.key('import_from_excel')}</DialogTitle>
        </DialogHeader>

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

        <Button

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

              //remove empty rows with empty first column
              data = data.filter((row) => row[0] !== null && row[0] !== undefined && row[0] !== "");

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

export default ReadExcelFileModal;
