'use client';

import { useState, useEffect } from 'react';

// MATERIAL - UI
import Modal from '@mui/material/Modal';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import CardContent from '@mui/material/CardContent';
import TextField from '@mui/material/TextField';
import CircularLoader from 'components/CircularLoader';

// PROJECT IMPORTS
import MainCard from 'components/MainCard';

//import async from '../../../app/(dashboard)/apps/e-commerce/product-details/[id]/page';
interface BasicModalProps {
  openModal: boolean;
  closeModel: () => void;
  save: (data: { icpInfo: string; calendlyLink: string; phone: string }) => void;
  isLoading: boolean;
  user: {
    icpInfo: string | null;
    calendlyLink: string | null;
    phone: string | null;
  };
}

// ==============================|| MODAL - BASIC ||============================== //

export default function CustomBasicInfoModal({ openModal, closeModel, save, isLoading , user }: BasicModalProps) {
  const [open, setOpen] = useState(openModal);
  const [icpInfo, setIcpInfo] = useState<string>(user?.icpInfo || '');           // ICP INFO field
  const [calendlyLink, setCalendlyLink] = useState<string>(user?.calendlyLink || ''); // Calendly Link field
  const [phone, setPhone] = useState<string>(user?.phone || ''); 
  const [inputError, setInputError] = useState({
    icpInfo: false,
    calendlyLink: false,
    phone: false,
  });

  useEffect(() => {
    setOpen(openModal); // Set modal open state when openModal prop changes
  }, [openModal]);

  const handleClose = () => closeModel();

  // Input change handlers
  const handleIcpInfoChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setIcpInfo(event.target.value);
    setInputError((prevState) => ({ ...prevState, icpInfo: false }));
  };

  const handleCalendlyLinkChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setCalendlyLink(event.target.value);
    setInputError((prevState) => ({ ...prevState, calendlyLink: false }));
  };

  const handlePhoneChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPhone(event.target.value);
    setInputError((prevState) => ({ ...prevState, phone: false }));
  };

  const handleSaveClick = async () => {
    const errors = {
      icpInfo: icpInfo.trim() === '',
      calendlyLink: calendlyLink.trim() === '',
      phone: phone.trim() === '',
    };
    setInputError(errors);

    // If there are no errors, save the data
    if (!errors.icpInfo && !errors.calendlyLink && !errors.phone) {
      save({ icpInfo, calendlyLink, phone });
    }
  };

  return (
    <>
      <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description">
        <MainCard title="Information" modal darkTitle content={false}>
        <CardContent>
            {/* ICP INFO Field */}
            <TextField
              label="ICP INFO"
              value={icpInfo}
              onChange={handleIcpInfoChange}
              fullWidth
              variant="outlined"
              margin="normal"
              error={inputError.icpInfo}
              helperText={inputError.icpInfo ? 'ICP INFO is required' : ''}
            />

            {/* Calendly Link Field */}
            <TextField
              label="Calendly Link"
              value={calendlyLink}
              onChange={handleCalendlyLinkChange}
              fullWidth
              variant="outlined"
              margin="normal"
              error={inputError.calendlyLink}
              helperText={inputError.calendlyLink ? 'Calendly Link is required' : ''}
            />

            {/* Phone Field */}
            <TextField
              label="Phone"
              value={phone}
              onChange={handlePhoneChange}
              fullWidth
              variant="outlined"
              margin="normal"
              error={inputError.phone}
              helperText={inputError.phone ? 'Phone is required' : ''}
            />
          </CardContent>
          <Divider />
          <Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ px: 2.5, py: 2 }}>
            <Button color="error" size="small" onClick={handleClose}>
              Cancel
            </Button>
            {isLoading ? (
              <CircularLoader />
            ) : (
              <Button variant="contained" size="small" onClick={handleSaveClick}>
                Submit
              </Button>
            )}
          </Stack>
        </MainCard>
      </Modal>
    </>
  );
}
