import React, { useEffect, useRef, useState } from 'react';
import { Icon } from './Icon';
import DeleteFacultyModal from '../roster/DeleteFacultyModal';
import ChangeTeamForm from '../roster/ChangeTeamForm';
import { Button, Modal } from 'react-bootstrap';
import { RosterData } from '../../pages/Roster';
import { useAuth } from '../../auth/AuthProvider';
import {
  deleteInstructor,
  deleteTA,
  deleteUser,
  getTAs,
  getInstructors,
  TA,
  Instructor,
} from '../../api/Users';
import { useToast } from '../Toast/ToastContext';
import { getOrders, updateOrder } from '../../api/Orders';

interface Props {
  id: number;
  first: string;
  last: string;
  email: string;
  type: string;
  isSelected: boolean;
  onClick: () => void;
  onDelete: (id: number) => void;
  className?: string;
  color?: string;
  rosterData: RosterData[];
  fetchUpdatedTeam: () => void;
  fetchUpdatedAdmin: () => void;
  isStudentView?: boolean;
}

const ProfileCard: React.FC<Props> = ({
  id,
  first,
  last,
  email,
  type,
  isSelected,
  onClick,
  onDelete,
  className,
  color,
  rosterData,
  fetchUpdatedTeam,
  fetchUpdatedAdmin,
  isStudentView = false,
}) => {
  const isStudentCard = className && className.includes('student-card');
  const isTACard = className && className.includes('ta-card');
  const [showModal, setShowModal] = useState(false); // State for modal visibility
  const [isInstructor, setIsInstructor] = useState(false);
  const [adminCard, setAdminCard] = useState(false);
  const [currentAdmin, setCurrentAdmin] = useState(false);

  const { user } = useAuth();

  const [copied, setCopied] = useState(false);
  //const [showTeamForm, setShowTeamForm] = useState(false);
  const { addToast } = useToast();

  useEffect(() => {
    if (type === 'instructor') {
      setIsInstructor(true);
      determineInstructorStatus();
    }
  }, [user]);

  const determineInstructorStatus = async () => {
    try {
      const instructors = await getInstructors();

      const currInstructor = instructors.find(
        (inst) => inst.user_id === user?.user_id
      ); // user of current login

      //console.log(currInstructor?.is_admin);
      const instructor = instructors.find((inst) => inst.user_id === id); // id of the profile card being passed in

      if (user?.type === 'instructor' && currInstructor?.is_admin === 'true') {
        //console.log('You are the admin!');
        setCurrentAdmin(true);
      }

      if (!isTACard && instructor?.is_admin === 'true') {
        //console.log('You are the admin!');
        setAdminCard(true);
      }
    } catch (error) {
    } finally {
      //setIsAdmin(false);
    }
  };

  const handleClose = () => setShowModal(false);

  const handleEditClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent triggering the card's onClick
    setShowModal(true); // Show the modal when trash icon is clicked
  };

  const handleChangeConfirm = () => {
    setShowModal(false);
  };

  const handleTrashClick = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent triggering the card's onClick
    setShowModal(true); // Show the modal when trash icon is clicked
    //console.log(id);
  };

  const handleDeleteConfirm = async () => {
    // delete admin
    const isTACard = className && className.includes('ta-card');
    //console.log(`Attempting to delete ${first} ${last}`);
    try {
      if (!isTACard) {
        const response = await getInstructors();
        let admin_id = 0;
        for (const instructor of response) {
          if (instructor.is_admin === 'true') {
            admin_id = instructor.instructor_id;
            break; // assuming only one admin
          }
        }
        const instructor = response.find(
          (instructor) => instructor.user_id === id
        );

        const orders = await getOrders(instructor?.instructor_id);
        for (const order of orders) {
          if (order.order_id !== undefined) {
            await updateOrder(order.order_id, {
              instructor_id: admin_id,
            });
          }
        }
      }
      await deleteUser(id);
      if (type === 'instructor')
        addToast('Instructor removed from roster.', 'success');
      else if (type === 'ta') addToast('TA removed from roster.', 'success');
      await fetchUpdatedAdmin();
    } catch (error) {
      addToast('Failed to remove user from roster.', 'danger');
      console.error('Error deleting admin:', error);
    }
    setShowModal(false); // Close the modal after confirming
  };

  const handleCopyEmail = (e: React.MouseEvent) => {
    e.stopPropagation();
    navigator.clipboard.writeText(email);
    // setCopied(true);
    // setTimeout(() => setCopied(false), 300); // 300ms flash
    addToast('Email copied to clipboard.', 'success');
  };

  const [shouldDisableChangeTeamButton, setShouldDisableChangeTeamButton] =
    useState(false);

  const [submitChangeTeamForm, setSubmitChangeTeamForm] = useState(false);
  const submitChangeTeamButton = useRef<HTMLButtonElement | null>(null);
  useEffect(() => {
    const handleKey = (event: { key: string }) => {
      if (event.key === 'Enter') {
        if (isStudentCard) {
          submitChangeTeamButton.current?.click();
        }
      }
    };

    if (showModal) {
      window.addEventListener('keydown', handleKey);
    } else {
      window.removeEventListener('keydown', handleKey);
    }
  }, [showModal]);

  return (
    <div
      className={`card ${className} `}
      onClick={onClick}
      style={{
        transition: 'transform 3s ease-in-out', // Smooth transition for the left move
        userSelect: 'none',
      }}
    >
      {/* Top-right Icon */}
      {!isStudentView &&
        !adminCard &&
        user?.email_address !== email &&
        ((user?.type === 'instructor' && user.type !== type) ||
          (user?.type !== 'instructor' && type === 'student') ||
          currentAdmin) && (
          <div
            role='button'
            tabIndex={0}
            onClick={isStudentCard ? handleEditClick : handleTrashClick} // Trigger the modal on click
            style={{
              position: 'absolute',
              top: '1rem',
              right: '1rem',
              cursor: 'pointer',
              zIndex: 1,
            }}
            className={`border rounded p-2`}
          >
            <div className='d-flex align-items-top'>
              {isStudentCard && (
                <Icon
                  iconName={'PencilSquare'} // Example icon name
                  style={{ fontSize: '20px', color: 'white' }}
                />
              )}
              {/* For Instructors */}
              {!isStudentCard &&
                !currentAdmin &&
                !adminCard &&
                user?.type === 'instructor' &&
                user.type !== type && (
                  <Icon
                    iconName={'Trash3Fill'} // Example icon name
                    style={{ fontSize: '20px', color: 'white' }}
                  />
                )}
              {/* For Admin */}
              {!isStudentCard &&
                currentAdmin &&
                !adminCard &&
                user?.email_address !== email && (
                  <Icon
                    iconName={'Trash3Fill'} // Example icon name
                    style={{ fontSize: '20px', color: 'white' }}
                  />
                )}
            </div>
          </div>
        )}

      <div
        className='card-header'
        style={{
          backgroundColor: color ? color : '#BEBEBE',
          color: 'white',
          display: 'flex',
          height: '150px',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        {/* <Avatar name={first + ' ' + last} size={50} bgColor='#6c757d' /> */}
        <Icon
          iconName='PersonCircle' // Use the icon name for the back arrow
          style={{
            fontSize: '40px',
            color: 'white', // White color for the icon
            //marginRight: '5px', // Add some space between the icon and the text
          }}
        />
      </div>

      <div className='card-body' style={{ textAlign: 'center' }}>
        <h5 className='card-title' style={{ marginBottom: '0rem' }}>
          {`${first} ${last}`}
        </h5>
        <p
          className='instructor-type'
          style={{
            marginBottom: '0rem',
            color: '#808080',
            fontSize: '0.875rem',
          }}
        >
          {adminCard
            ? 'Admin'
            : type === 'instructor' && !adminCard
              ? 'Instructor'
              : type === 'ta'
                ? 'TA'
                : 'Student'}
        </p>
        <p
          className='card-text d-flex justify-content-center align-items-center'
          style={{ marginBottom: '0', color: '#808080' }}
        >
          <span>{email}</span>
          <span
            role='button'
            onClick={handleCopyEmail}
            style={{
              cursor: 'pointer',
              transition: 'background-color 0.3s ease-in-out',
              display: 'inline-block',
            }}
            title='Copy email'
            className='ms-2'
          >
            <Icon
              iconName='Copy'
              style={{
                fontSize: '16px',
                color: copied ? '#FFFFFF' : '#808080',
              }}
            />
          </span>
        </p>
      </div>

      {/* Modal */}
      {isStudentCard && (
        <Modal show={showModal} onHide={() => setShowModal(false)}>
          <Modal.Header closeButton>
            <Modal.Title>Change Team</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className='mb-3'>
              You are changing the team assignment for{' '}
              <b>
                {first} {last}
              </b>
              .
            </div>
            <hr />
            <div className='mb-2'>
              <ChangeTeamForm
                rosterData={rosterData}
                id={id}
                onClose={() => setShowModal(false)}
                onTeamChange={() => {
                  setShowModal(false); // Close the form
                  fetchUpdatedTeam(); // Refresh the users list
                }}
                setShouldDisableButton={setShouldDisableChangeTeamButton}
                submit={submitChangeTeamForm}
                setSubmit={setSubmitChangeTeamForm}
              />
            </div>
          </Modal.Body>
          <Modal.Footer>
            <Button variant='secondary' onClick={() => setShowModal(false)}>
              Cancel
            </Button>
            <Button
              ref={submitChangeTeamButton}
              variant='primary'
              onClick={() => setSubmitChangeTeamForm(true)}
              disabled={shouldDisableChangeTeamButton}
            >
              Change Team
            </Button>
          </Modal.Footer>
        </Modal>
      )}

      {!isStudentCard && (
        <DeleteFacultyModal
          show={showModal}
          handleClose={handleClose}
          title={'Delete Faculty'}
          userName={`${first} ${last}`}
          isInstructor={type === 'instructor'}
          onPrimaryAction={() => {
            handleDeleteConfirm();
            fetchUpdatedAdmin();
          }}
        />
      )}
    </div>
  );
};

export default ProfileCard;
