import React, { createContext, useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '@/i18n';
import { DefaultTooltip, KeenIcon } from '@/components';
import { Button } from '@/components/ui/button';
import { apiConfig } from '@/config/api.config';
import { Stepper, Step, StepLabel } from '@mui/material';
import { StepOne, StepTwo, StepThree, StepFour } from '../steps';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import { doSaveLogActivity } from '@/actions/GlobalActions';

const API_URL = apiConfig.service_credit;
const CreditAddContext = createContext<any | null>(null);

const steps = ['Step 1', 'Step 2', 'Step 3', 'Step 4'];

const initialState = {
  name: '',
  employee_id: '',
  phone: '',
  application_date: '',
  identity_type: '',
  identity_file: '',
  companyId: '', // => wajib
  type: '',
  marriage_type: '',
  marriage_file: '', //Surat Keterangan Menikah
  family_file: '', // Kartu keluarga
  form: [],
  spouse_type: '',
  spouse_file_type: '',
  spouse_file: '',
  photo: '',
  spouse_photo: '',
  account_number: '',
  amount: '',
  period_amount: '',
  period_type: '',
  status: '',
  description: ''
};

// console.log('initialState:', initialState);

const CreditAddContextProvider = ({ children }: { children: React.ReactNode }) => {
  const navigate = useNavigate();

  const [activeStep, setActiveStep] = useState(0);
  const [formData, setFormData] = useState(initialState);
  const { PostData } = useCallApi();
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  type State = typeof initialState; // Gunakan tipe otomatis dari initialState

  const validateState = (state: State): Record<string, string> => {
    const errors: Record<string, string> = {};

    if (!state.companyId || state.companyId.trim() === '') {
      errors.companyId = 'Instansi pengaju harus diisi.';
    }
    return errors;
  };

  const handleBackClick = () => navigate('/pengajuan_kredit/list');

  const handleNext = () => {
    if (activeStep < steps.length - 1) {
      if (activeStep === 0) {
        const errors = validateState(formData);
        if (Object.keys(errors).length > 0) {
          toast.error(errors.companyId);
          return;
        }
      }
      setActiveStep((prevStep) => prevStep + 1);
    } else {
      handleSubmit();
    }
  };

  const handleBack = () => setActiveStep((prev) => prev - 1);

  const handleSaveToDraft = () => {
    setFormData((prev: any) => ({ ...prev, status: 'draft' }));
  };

  const handleSubmit = () => {
    setFormData((prev: any) => ({ ...prev, status: 'open' }));
  };

  useEffect(() => {
    if (formData.status !== '') {
      doCreateCredit(formData);
    }
  }, [formData]);

  const renderStepContent = (step: number) => {
    switch (step) {
      case 0:
        return <StepOne setFormData={setFormData} formData={formData} />;
      case 1:
        return <StepTwo setFormData={setFormData} formData={formData} />;
      case 2:
        return <StepThree setFormData={setFormData} formData={formData} />;
      case 3:
        return <StepFour setFormData={setFormData} formData={formData} />;
      default:
        return <div>Langkah tidak dikenal</div>;
    }
  };

  const resetForm = () => {
    setFormData(initialState);
  };

  const doCreateCredit = useCallback(async (updatedFormData: typeof formData) => {
    console.log('formData: ', updatedFormData);

    const response = await PostData(`${API_URL}/application/create`, updatedFormData);
    if (response?.status) {
      setAlert((prev) => ({ ...prev, show: false, message: '' }));
      toast.success('Success Create New Credit');
      resetForm();
      const createActivity = {
        module: 'Create Pengajuan Credit',
        description: `Add new data Credit for => ${updatedFormData?.name}`,
        action: 'C'
      };
      doSaveLogActivity(createActivity);
      handleBackClick();
    } else {
      setAlert((prev) => ({ ...prev, show: true, message: response?.message }));
    }
  }, []);

  return (
    <div className="flex justify-center">
      <div className="px-5 lg:w-9/12 w-full" style={{ marginTop: '-1.25rem' }}>
        {/* Header */}
        <div className="flex justify-between items-center mb-5">
          <div className="flex items-center">
            <DefaultTooltip title="Back to list" placement="top">
              <Button
                variant="outline"
                className="h-7.5 border-0 px-0 me-[14px]"
                style={{ marginLeft: -5 }}
                onClick={handleBackClick}
              >
                <KeenIcon icon="arrow-left" className="text-[20px] px-1 card-title" />
              </Button>
            </DefaultTooltip>
            <p className="font-semibold text-[16px] card-title">Pengajuan Kredit</p>
          </div>
        </div>

        {/* Stepper */}
        <Stepper activeStep={activeStep}>
          {steps.map((label, index) => (
            <Step key={index} style={{ marginRight: '-16px', marginLeft: '-8px' }}>
              <StepLabel></StepLabel>
            </Step>
          ))}
        </Stepper>

        {/* Step Content */}
        {activeStep === steps.length ? (
          <div className="">
            <p style={{ marginTop: 2, marginBottom: 1 }}>
              Semua langkah selesai - Anda telah menyelesaikan proses
            </p>
          </div>
        ) : (
          <div>
            <p className="mt-3 mb-5 text-[12px] text-gray-500">Langkah {activeStep + 1}/4</p>
            {renderStepContent(activeStep)}
            <div style={{ display: 'flex', flexDirection: 'row', paddingTop: '16px' }}>
              {activeStep !== 0 && (
                <Button
                  className="me-5 text-[14px] w-48 btn btn-outline-secondary bg-gray-200 text-gray-800"
                  style={{ borderRadius: 50 }}
                  disabled={activeStep === 0}
                  onClick={handleBack}
                >
                  Kembali
                </Button>
              )}
              {activeStep === steps.length - 1 && (
                <Button
                  className="me-5 text-[14px] w-48 btn btn-outline-secondary bg-gray-200 text-gray-800"
                  style={{ borderRadius: 50 }}
                  onClick={handleSaveToDraft}
                >
                  Simpan ke Draft
                </Button>
              )}
              <Button
                className="text-[14px] w-full btn btn-primary bg-primary"
                style={{ borderRadius: 50, backgroundColor: '#00519D' }}
                onClick={handleNext}
              >
                {activeStep === steps.length - 1 ? 'Kirim Pengajuan' : 'Selanjutnya'}
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export { CreditAddContext, CreditAddContextProvider };
