'use client';

import { useState, useEffect } from 'react';
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 Box from '@mui/material/Box';
import CardContent from '@mui/material/CardContent';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import { checkUserExists, fetchAccountUsers, getAllArchielist, saveNewProfile } from 'api/table3handler';
import { PrismaClient } from '@prisma/client';
import toast from 'react-hot-toast';

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

// Interface for account users
interface AccountUser {
  id: number;
  fullName: string;
}

// Props for the modal component
interface ProfileModalProps {
  openModal: boolean;
  closeModal: () => void;
  saveProfile: (profileName: string, profileId: number) => void;
  isLoading: boolean;
}

const prisma = new PrismaClient();

export default function ProfileModal({ openModal, closeModal, isLoading, saveProfile, setData }: any) {
  const [profileNames, setProfileNames] = useState<AccountUser[]>([]); // Change to store multiple profiles
  const [accountUsers, setAccountUsers] = useState<AccountUser[]>([]);
  const [loading, setLoading] = useState(false);

  // Fetch account users on component mount
  useEffect(() => {
    const loadAccountUsers = async () => {
      setLoading(true);
      const users = await fetchAccountUsers();
      setAccountUsers(users);
      setLoading(false);
    };

    loadAccountUsers();
  }, []);

  // Function to check if the user exists and save if not
  const handleSaveClick = async () => {
    if (profileNames.length > 0) {
      try {
        // Loop over selected profiles
        setLoading(true);
        for (const user of profileNames) {
          const userExists = await checkUserExists(user.id);

          if (userExists.length > 0) {
            // toast.error(`User ${user.fullName} already exists`);
          } else {
            await saveNewProfile(user.id);
            // toast.success(`Profile for ${user.fullName} saved successfully!`);
            // saveProfile(user.fullName, user.id);
          }
        }

        // Show final success message
        toast.success('Profiles successfully added to Auto Archived List!');

        // Close modal and fetch updated list after all profiles are saved
        closeModal();
        setProfileNames([]);
        const result = await getAllArchielist();
        setData(result);
      } catch (error) {
        console.error('Error during profile save:', error);
        toast.error('An error occurred while saving the profile.');
        setLoading(false);
      } finally {
        setLoading(false);
      }
    } else {
      toast.error('Please select at least one profile');
    }
  };

  return (
    <Modal open={openModal} onClose={closeModal} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description">
      <Box display="flex" justifyContent="center" alignItems="center" height="100vh">
        <MainCard title="Select Profile Names" modal darkTitle content={false} sx={{ width: 400, maxWidth: '90%' }}>
          <CardContent>
            <Box display="flex" flexDirection="column" alignItems="center">
              {loading ? (
                <CircularLoader />
              ) : (
                <Box display="flex" justifyContent="center" width="100%">
                  <Autocomplete
                    multiple // Allow multiple selection
                    options={accountUsers}
                    getOptionLabel={(option) => option.fullName}
                    value={profileNames}
                    onChange={(event, newValue) => setProfileNames(newValue)}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label="Search Profile Names"
                        variant="outlined"
                        fullWidth
                        margin="normal"
                        sx={{
                          width: '100%',
                          maxWidth: '600px',
                          minWidth: '350px',
                          fontSize: '1.5rem'
                          // padding: '5px'
                        }}
                      />
                    )}
                    isOptionEqualToValue={(option, value) => option.id === value.id}
                  />
                </Box>
              )}
            </Box>
          </CardContent>
          <Divider />
          <Stack direction="row" spacing={2} justifyContent="flex-end" sx={{ px: 3, py: 2 }}>
            <Button color="error" onClick={closeModal}>
              Close
            </Button>
            {loading ? (
              // <CircularLoader />
              <Button variant="contained" onClick={handleSaveClick} disabled={true}>
                Processing
              </Button>
            ) : (
              <Button variant="contained" onClick={handleSaveClick}>
                Save
              </Button>
            )}
          </Stack>
        </MainCard>
      </Box>
    </Modal>
  );
}
