import { MouseEvent, useCallback, useEffect, useRef, useState } from 'react';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';

import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog';
import { useTransactionContext } from '../hooks';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Alert, KeenIcon, useDataGrid } from '@/components';
import { toast } from 'sonner';
import { useCallApi } from '@/hooks';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import clsx from 'clsx';

const API_URL = apiConfig.service_disbursement;

const UploadBatchDialog = () => {
  const parentRef = useRef<any | null>(null);
  const { showUploadBatchDialog, handleUploadBatchDialog } = useTransactionContext();
  const { reload } = useDataGrid();
  const { PostData, PostDataFile, GetData } = useCallApi();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });
  const initialState: {
    execution_date: string,
    file: File | null;
  } = {
    execution_date: '',
    file: null
  }
  const [formField, setFormField] = useState(initialState);

  const resetForm = () => {
    setFormField(initialState);
    setAlert({ show: false, message: '' });
  };

  /* actions */
  const doUploadBatch = useCallback(
    async (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault();
  
      const formData = new FormData();
      formData.append('execution_date', formField.execution_date);
      if (formField.file) {
        formData.append('file', formField.file);
      }
  
      try {
        const response = await PostDataFile(`${API_URL}/upload-excel`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
  
        if (response?.status) {
          handleUploadBatchDialog(false);
          resetForm();
          reload();
  
          const createActivity = {
            module: 'Disbursement',
            description: `Create New Disbursement => ${formField.file?.name}`,
            action: 'C'
          };
  
          doSaveLogActivity(createActivity);
          toast.success('Success Create Disbursement');
        } else {
          toast.error('Failed to create disbursement');
          setAlert({ show: true, message: response?.message ?? 'Failed to create disbursement.' });
        }
      } catch (error) {
        toast.error('Error uploading batch');
        setAlert({ show: true, message: 'Something went wrong. Please try again.' });
      }
    },
    [formField]
  );

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    console.log('Form data before submit:', formField);

    if (
      formField.execution_date.trim() === '' || 
      formField.file === null
    ) {
      setAlert({ show: true, message: 'Please fill in all required fields.' });
      return;
    }

    doUploadBatch(e);
    // console.log(formField);
    setAlert({ show: false, message: '' });
  };
  
  useEffect(() => {
    if (showUploadBatchDialog === false) {
      resetForm();
    }
  }, [showUploadBatchDialog]);

  return (
    <Dialog open={showUploadBatchDialog} onOpenChange={(open) => handleUploadBatchDialog(open)}>
      <DialogContent className="container-fixed max-w-[768px] flex flex-col p-5 overflow-hidden [&>button]:hidden">
        <DialogHeader className="p-0 border-0">
          <DialogTitle></DialogTitle>
          <DialogDescription></DialogDescription>
          <div className="flex items-center justify-between flex-wrap grow">
            <div className="flex flex-col justify-center">
              <h1 className="text-xl font-semibold leading-none text-gray-900">Upload Batch</h1>
              <div className="flex items-center gap-2 text-sm font-normal text-gray-700"></div>
            </div>
            <div
              className="cursor-pointer hover:opacity-100 opacity-50"
              onClick={() => {
                handleUploadBatchDialog(false);
                resetForm();
              }}
            >
              <KeenIcon icon="cross" className="text-1.5xl" />
            </div>
          </div>
        </DialogHeader>
        <DialogBody className="scrollable-y px-0 pb-0" ref={parentRef}>
          <div className="flex flex-col px-0">
            {alert.show && (
              <Alert variant="danger" className="mb-3">
                <h3>{alert.message}</h3>
              </Alert>
            )}
            <form action="" onSubmit={handleSubmit}>
              <div className="card-body grid gap-5 p-0">
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">Execution Date</label>
                    <Input
                      className="input"
                      type="datetime-local"
                      autoComplete="off"
                      value={formField.execution_date}
                      required
                      onChange={({ target }) =>
                        setFormField((prev) => ({ ...prev, execution_date: target.value }))
                      }
                    />
                  </div>
                </div>
                <div className="w-full">
                  <div className="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5">
                    <label className="form-label flex items-center gap-1 max-w-56">File</label>
                    <Input
                        className="input"
                        type="file"
                        autoComplete="off"
                        required
                        onChange={({ target }) =>
                            setFormField((prev) => ({ ...prev, file: target.files?.[0] ?? null }))
                        }
                    />
                  </div>
                </div>
                <div className="flex justify-end pt-2.5">
                  <Button className="btn btn-primary" type="submit">
                    Save Changes
                  </Button>
                </div>
              </div>
            </form>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
};

export { UploadBatchDialog };
