import { useRef, useState } from 'react';
import { IconCloudUpload, IconDownload, IconX } from '@tabler/icons-react';
import { Button, Group, Text, useMantineTheme } from '@mantine/core';
import { Dropzone } from '@mantine/dropzone';
import classes from './AirportDrop.module.css';
import { importAirports } from '@lib/airport.ts';

export function AirportDrop() {
  const theme = useMantineTheme();
  const openRef = useRef<() => void>(null);
  const [loading, setLoading] = useState(false);

  return (
    <div className={classes.wrapper}>
      <Dropzone
        loading={loading}
        openRef={openRef}
        onDrop={async (files) => {
          if (files.length === 0) return;
          setLoading(true);
          try {
            const formData = new FormData();
            files.forEach(file => {
              formData.append('files', file, file.name);
            })
            await importAirports(formData);
          } catch (error) {
            console.error('Upload error:', error);
          } finally {
            setLoading(false);
          }
        }}
        className={classes.dropzone}
        radius="md"
        accept={['application/JSON']}
        maxSize={30 * 1024 ** 2}
      >
        <div style={{ pointerEvents: 'none' }}>
          <Group justify="center">
            <Dropzone.Accept>
              <IconDownload size={50} color={theme.colors.blue[6]} stroke={1.5} />
            </Dropzone.Accept>
            <Dropzone.Reject>
              <IconX size={50} color={theme.colors.red[6]} stroke={1.5} />
            </Dropzone.Reject>
            <Dropzone.Idle>
              <IconCloudUpload size={50} stroke={1.5} className={classes.icon} />
            </Dropzone.Idle>
          </Group>

          <Text ta="center" fw={700} fz="lg" mt="xl">
            <Dropzone.Accept>Drop files here</Dropzone.Accept>
            <Dropzone.Reject>Json file less than 30mb</Dropzone.Reject>
            <Dropzone.Idle>Upload JSON</Dropzone.Idle>
          </Text>

          <Text className={classes.description}>
            Drag&apos;n&apos;drop files here to upload. We can accept only <i>.json</i> files that
            are less than 30mb in size.
          </Text>
        </div>
      </Dropzone>

      <Button className={classes.control} size="md" radius="xl" onClick={() => openRef.current?.()}>
        Select files
      </Button>
    </div>
  );
}