import React, { useRef, useState } from 'react';
import styled from 'styled-components';
import { Button } from '@bjsdistribution/dms-component-library';
import UploadIcon from '../../../../../assets/icons/UploadIcon';
import { atom, useAtom } from 'jotai';
import { notification } from 'antd';

export const uploadedFilesAtom = atom<File[]>([]);

// Allowed photo and video file types
const fileTypes = ['image/jpeg', 'image/png', 'video/mp4'];

function DocFileUpload() {
  const [uploadedFiles, setUploadedFiles] = useAtom(uploadedFilesAtom);
  const [dragging, setDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileUpload = (files: FileList | null) => {
    if (files) {
      const validFiles = Array.from(files).filter(file =>
        fileTypes.includes(file.type)
      );

      if (validFiles.length > 0) {
        setUploadedFiles(prev => [...prev, ...validFiles]);
        validFiles.forEach(file => {
          notification.success({
            message: 'Success',
            description: `${file.name} added successfully.`,
          });
        });
      } else {
        notification.error({
          message: 'Error',
          description: 'Only photos (JPEG, PNG) and videos (MP4) are allowed.',
        });
      }
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(true);
  };

  const handleDragLeave = () => {
    setDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    handleFileUpload(e.dataTransfer.files);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleFileUpload(e.target.files);
  };

  const handleButtonClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  return (
    <MainContainer>
      <DraggerContainer
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        dragging={dragging}
      >
        <Container>
          <UploadButton
            colors="secondary"
            shape="rounded"
            onClick={handleButtonClick}
          >
            UPLOAD FILE
          </UploadButton>
          <FileInput
            type="file"
            required
            multiple
            onChange={handleInputChange}
            accept="image/jpeg, image/png, video/mp4"
            ref={fileInputRef}
          />
          <IconContainer>
            <UploadIcon />
          </IconContainer>
          <TextContainer>
            <Text1>or drag and drop your file </Text1>
            <Text2>Photos (JPEG, PNG) or Videos (MP4) Only</Text2>
          </TextContainer>
        </Container>
      </DraggerContainer>

      {/* Uploaded Files List */}
      {uploadedFiles.length > 0 && (
        <UploadedFilesContainer>
          <FilesTitle>Uploaded Files:</FilesTitle>
          <FilesList>
            {uploadedFiles.map((file, index) => (
              <FileItem key={index}>
                {file.name} - {(file.size / 1024).toFixed(2)} KB
              </FileItem>
            ))}
          </FilesList>
        </UploadedFilesContainer>
      )}
    </MainContainer>
  );
}

const MainContainer = styled.div`
  width: 100%;
`;

const DraggerContainer = styled.div<{ dragging: boolean }>`
  width: 100%;
  padding: 6px;
  border-radius: 30px;
  border: ${props =>
    props.dragging ? '2px dashed #0465ac' : '1px solid #e0e2e7'};
  background-color: #fff;
  transition: border-color 0.3s ease;
  cursor: pointer;
`;

const Text2 = styled.p`
  color: #bcbab7;
  text-align: center;
  font-family: 'Roboto', sans-serif;
  font-size: 13px;
  font-style: normal;
  font-weight: 400;
  text-transform: lowercase;
  padding: 0;
  margin: 0;
`;

const TextContainer = styled.div``;

const Text1 = styled.p`
  color: #aea9a1;
  text-align: left;
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  text-transform: lowercase;
  padding: 0;
  margin: 0;
`;

const IconContainer = styled.div`
  border: 1px dashed #0465ac;
  padding: 5px;
  display: flex;
  align-items: center;
`;

const UploadButton = styled(Button)`
  height: 16px;
  font-size: 14px;
  padding: 7px 20px;
`;

const Container = styled.div`
  display: flex;
  gap: 8px;
  padding: 6px;
  align-items: center;
  align-self: stretch;
  border-radius: 30px;
  background: #fff;
`;

const FileInput = styled.input`
  display: none;
`;

const UploadedFilesContainer = styled.div`
  margin-top: 20px;
  border-top: 1px solid #e0e2e7;
  padding-top: 10px;
`;

const FilesTitle = styled.h4`
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  color: #0465ac;
`;

const FilesList = styled.ul`
  list-style-type: none;
  padding: 0;
`;

const FileItem = styled.li`
  font-family: 'Roboto', sans-serif;
  font-size: 14px;
  color: #333;
  margin: 5px 0;
`;

export default DocFileUpload;
