import React, { useState, FormEvent } from 'react';
import { Button, Modal, Spin } from 'antd';

const App: React.FC = () => {
  const [moduleName, setModuleName] = useState('');
  const [moduleType, setModuleType] = useState('');
  const [open, setOpen] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);

  const handleModuleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const data = {
      moduleName,
      moduleType,
    };
    setLoading(true);
    try {
      const response = await fetch(`https://api.teachertrainingkolkata.in/api/create-module`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        throw new Error('Network Response not ok');
      }
      const result = await response.json();
      console.log('Success', result);
      setOpen(false); // Close the modal on successful submission
    } catch (error) {
      console.error('Error', error);
    } finally {
      setLoading(false);
    }
  };

  const showLoading = () => {
    setOpen(true);
    setLoading(true);

    // Simple loading mock. You should add cleanup logic in the real world.
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  return (
    <>
      <Button type="primary" onClick={showLoading}>New Module</Button>
      <Modal
        title="Loading Modal" centered
        footer={false}
        open={open}
        onCancel={() => setOpen(false)}
      >
        {loading ? (
          <Spin size="large" />
        ) : (
          <div className='container mx-auto px-4'>
            <form onSubmit={handleModuleSubmit} className='flex flex-col'>
              <div className='flex flex-col mb-4'>
                <label htmlFor="moduleName">Module Name:</label>
                <input className='border-[1px] border-[#CFCFCF] focus:outline-none focus:border-[#EF7A0C] rounded-[8px] p-2' value={moduleName} onChange={(e) => setModuleName(e.target.value)} type="text" name='moduleName' id='moduleName' />
              </div>
              <div className='flex flex-col'>
                <label htmlFor="moduleType">Module Type:</label>
                <input className='border-[1px] border-[#CFCFCF] focus:outline-none focus:border-[#EF7A0C] rounded-[8px] p-2' value={moduleType} onChange={(e) => setModuleType(e.target.value)} type="text" name='moduleType' id='moduleType' />
              </div><br />
              <button className='bg-[#000] py-2.5 text-[#FFF] rounded-[10px]' type="submit">Submit</button>
            </form>
          </div>
        )}
      </Modal>
    </>
  );
};

export default App;
