import ContentCard from '../components/shared/ContentCard';
import RequestForm from '../components/RequestForm/RequestForm';
import { User } from '../api/Users';
import UserDirectory from '../components/RequestForm/UserDirectory';
import { useEffect, useState } from 'react';
import { DataTable } from '../components/shared/DataTable';
import {
  defaultRequestColumns,
  getRequests,
  RequestTableData,
  transformRequests,
} from '../api/Requests';
import { FetchError } from '../utils/FetchHelper';
import { useAuth } from '../auth/AuthProvider';

export const InstructorRequests = () => {
  const { user } = useAuth();
  const [selectedUser, setSelectedUser] = useState<User | undefined>(undefined);
  const [selectedViewUser, setSelectedViewUser] = useState<User | undefined>(
    undefined
  );
  const [transformedRequests, setTransformedRequests] = useState<
    RequestTableData[]
  >([]);

  const fetchAllRequests = async () => {
    if (selectedViewUser) {
      fetchRequestsForSelectedUser();
      return;
    }

    const result = await getRequests();
    if (result) {
      const transformedResult = await transformRequests(result);
      setTransformedRequests(transformedResult);
    }
  };

  const fetchRequestsForSelectedUser = async () => {
    if (selectedViewUser == undefined) {
      return;
    }

    let result;
    if (
      selectedViewUser &&
      selectedViewUser.student_id &&
      selectedViewUser.team_id
    ) {
      result = await getRequests(
        selectedViewUser.student_id,
        selectedViewUser.team_id
      );
    } else {
      console.error('Please select a user with a team and student id');
    }

    if (result) {
      const transformedResult = await transformRequests(result);
      if (transformedResult instanceof FetchError) {
        if (transformedResult.status === undefined) {
          console.error(transformedResult.message);
        } else {
          console.error(
            `HTTP error ${transformedResult.status}: ${transformedResult.message}`
          );
        }
      } else {
        setTransformedRequests(transformedResult);
      }
    }
  };

  useEffect(() => {
    fetchRequestsForSelectedUser();
  }, [selectedViewUser]);

  useEffect(() => {
    fetchAllRequests();
  }, [user, selectedViewUser]);

  return (
    <div>
      <ContentCard
        title='View Placed Requests'
        description='View all requests placed to date, and optionally select a student to restrict results to their submissions.'
      >
        <UserDirectory onSelectUser={setSelectedViewUser} />
        <DataTable
          columns={defaultRequestColumns}
          data={transformedRequests}
          setData={setTransformedRequests}
        />
      </ContentCard>
      <ContentCard
        title='New Instructor Request'
        description='Select a student from the dropdown to place a new request on their behalf. Part information may be autofilled based on matching part URLs.'
      >
        <UserDirectory onSelectUser={setSelectedUser} />
        <RequestForm
          selectedUser={selectedUser ?? user}
          onRequestSubmit={fetchAllRequests}
        />
      </ContentCard>
    </div>
  );
};
