import React, { useEffect, useState } from 'react';
import { useCallApi } from '@/hooks';
import { KeenIcon } from '@/components';
import { ImageInput, IImageInputFile } from '@/components/image-input';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';

const API_URL = apiConfig.service_credit;

const StepThree = ({ setFormData, formData }: any) => {
  const [imageFiles, setImageFiles] = useState<{ [key: string]: IImageInputFile[] }>({});
  const [formList, setFormList] = useState<any[]>([]);
  const { PostData, GetData } = useCallApi();

  const uploadFile = async (file: File, name: string, id: string) => {
    // console.log(file);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await PostData(`${API_URL}/application/file/upload`, formData);

      if (response?.status) {
        toast.success('Success upload document');
        // let obj = { [name]: response.message.name };
        let form = {
          id: id,
          name: name,
          type: 'file',
          value: response?.message.name
        };
        console.log('form:', form);
        setFormData((prevState: any) => ({
          ...prevState,
          form: [...prevState.form, form] // Tambahkan form ke array form
        }));
      }
    } catch (error) {
      console.error('Error uploading file:', error);
    }
  };
  const handleImageChange = (name: string, id: string) => (value: IImageInputFile[]) => {
    setImageFiles((prev) => ({
      ...prev,
      [name]: value
    }));

    value.forEach((item) => {
      if (item.file) {
        uploadFile(item.file, name, id);
      }
    });
  };

  const doGetFormList = async (code: string) => {
    const response = await GetData(`${API_URL}/application/form/list`, {
      code: formData?.type
    });
    return { data: response?.data };
  };

  useEffect(() => {
    const fetchFormList = async () => {
      try {
        const { data } = await doGetFormList(formData?.type);
        setFormList(data);
      } catch (error) {
        console.error('Failed to fetch form type', error);
      }
    };
    fetchFormList();
  }, []);

  return (
    <div className="mb-5" style={{ minHeight: '53vh' }}>
      <div className="">
        <p className="text-[14px] form-label">Persyaratan Lain</p>
      </div>
      <hr className="border-dashed my-3 border-gray-300" />
      <div className="grid lg:grid-cols-2 gap-y-5 lg:gap-5 items-stretch">
        {formList.map((type, index) => (
          <div key={index} className="flex flex-col justify-between">
            <div className="mb-2">
              <label className="form-label flex items-center gap-1 text-[13px]">{type.label}</label>
              <p className="text-danger text-[13px]">{type.label_red}</p>
            </div>
            <ImageInput
              value={imageFiles[type.name]}
              onChange={handleImageChange(type.name, type.id)}
              multiple={false}
            >
              {({ fileList, onImageUpload, onImageRemove, dragProps, isDragging }) => (
                <button onClick={onImageUpload} className="text-[13px] text-gray-500 w-full">
                  <div
                    {...dragProps}
                    style={{
                      border: isDragging ? '1px dashed #4CAF50' : '1px dashed #006599',
                      padding: '20px',
                      textAlign: 'center',
                      borderRadius: '0.375rem',
                      minHeight: '152px',
                      alignItems: 'center',
                      justifyContent: 'center',
                      display: 'flex'
                    }}
                  >
                    <div>
                      <KeenIcon icon="file-up" className="text-[20px] px-1 card-title" />
                      {fileList.length > 0 ? (
                        fileList.map((file, index) => (
                          <div key={index}>
                            <p>{file.file?.name}</p>
                            <button onClick={() => onImageRemove(index)} className="text-danger">
                              Hapus
                            </button>
                          </div>
                        ))
                      ) : (
                        <div className="">Click here to import file</div>
                      )}
                    </div>
                  </div>
                </button>
              )}
            </ImageInput>
          </div>
        ))}
      </div>
    </div>
  );
};

export { StepThree };
