import React, { useEffect, useState } from 'react';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import DocumentTypeDropdown from './DocumentTypeDropdown';
import styled from 'styled-components';
import CategoryDropdown from './CategoryDropdown';
import VisibilityRadioButtons from './Visibility';
import DocFileUpload, { uploadedFilesAtom } from './DocFileUpload';
import {
  useAtom,
  useCurrentAction,
  useCustomerInfo,
  useOrderId,
  useOrderStaticData,
} from '../../../store';
import {
  selectedCategoryIdAtom,
  selectedDocumentTypeAtom,
  selectedTypeAtom,
  selectedVisibilityAtom,
  setResourcesCall,
} from '../../store';
import OrderActionsDropdown from '../../Dropdown';
import { notification } from 'antd';
import { useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../../types';

function AddResources() {
  const [, setCurrentAction] = useCurrentAction();
  const [staticOrderData] = useOrderStaticData();
  const [, setSelectedType] = useAtom(selectedTypeAtom);
  const [uploadedFiles, setUploadedFiles] = useAtom(uploadedFilesAtom);
  const [isFormValid, setIsFormValid] = useState(false);
  const [selectedCategoryId] = useAtom(selectedCategoryIdAtom);
  const [selectedDocumentType] = useAtom(selectedDocumentTypeAtom);
  const [selectedType] = useAtom(selectedTypeAtom);
  const [, setResources] = useAtom(setResourcesCall);
  const [orderId] = useOrderId();
  const [selectedVisibility] = useAtom(selectedVisibilityAtom);

  //add resources POST API
  const { fetchData: callResourcesAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/${orderId}/order_resources/?document_type=${selectedDocumentType}&type=${selectedType}&category=${selectedCategoryId}&visibility=${selectedVisibility}`,
    method: 'POST',
  });

  const onClose = () => {
    setCurrentAction(undefined);
    setUploadedFiles([]);
  };

  const [customerInfo] = useCustomerInfo();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;
  const typeOptions = staticOrderData?.resource_type?.map((x: any) => ({
    id: x?.id,
    type: x?.type,
    value: x?.value,
  }));

  const onSelectCancelReason = (selectedValue: any) => {
    const selectedOption = typeOptions?.find(
      (option: any) => option?.value === selectedValue
    );
    if (selectedOption) {
      setSelectedType(selectedOption.value);
    }
  };
  console.log(uploadedFiles, 'filesfiles');
  const handleSubmit = async () => {
    if (!uploadedFiles) {
      notification.error({ message: 'No files selected' });
      return;
    }

    const formData = new FormData();
    if (uploadedFiles) {
      Array.from(uploadedFiles).forEach(uploadedFiles => {
        formData.append('files', uploadedFiles); // Adjust the key as per your API requirement
      });
    }

    try {
      let response = (await callResourcesAPI({
        payload: formData,
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      console.log('Upload successful:', response);
      notification.success({ message: 'Files uploaded successfully' });
      onClose(); // Close modal after successful upload
      setResources(false);

      setTimeout(() => {
        setResources(true);
      }, 1000);
    } catch (error) {
      console.error('Upload failed:', error);
    }
  };

  useEffect(() => {
    setIsFormValid(
      !!selectedType &&
        !!selectedDocumentType &&
        !!selectedCategoryId &&
        uploadedFiles?.length > 0
    );
  }, [selectedDocumentType, selectedCategoryId, uploadedFiles]);

  return (
    <OrderActionModal
      headerTitle="ADD RESOURCE"
      showAdditionalInfo
      infoText={infoText}
      onCloseHeader={onClose}
      onSubmit={handleSubmit}
      isSubmitDisabled={!isFormValid}
    >
      <ContentContainer>
        <Top>
          <DocumentTypeDropdown />

          <OrderActionsDropdown
            label="Type"
            required
            placeholder="Select Type"
            options={typeOptions}
            onSelect={onSelectCancelReason}
          />

          <CategoryDropdown />
          <VisibilityRadioButtons />
        </Top>
        <Bottom>
          <Label>File</Label> <RequiredAsterisk>*</RequiredAsterisk>
          <DocFileUpload />{' '}
        </Bottom>
      </ContentContainer>
    </OrderActionModal>
  );
}
const RequiredAsterisk = styled.span`
  color: red;
  margin-left: 2px;
`;
const Label = styled.label`
  color: #6a7378;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
`;

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

const Top = styled.div`
  display: flex;
  gap: 15px;
  > div {
    min-width: 240px;
  }
`;

const ContentContainer = styled.div`
  padding: 15px 12px;
  flex: 1 0 0;
  border-radius: 15px;
  background: #f8fafc;
  margin: 0px 20px 0 20px;
`;

export default AddResources;
