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

export const StudentRequests = () => {
  const { user } = useAuth();
  const [transformedRequests, setTransformedRequests] = useState<
    RequestTableData[]
  >([]);

  const fetchRequests = async () => {
    const students = await getStudents();
    let student;
    if (user) {
      student = students.find((student) => user.user_id === student?.user_id);
    }
    if (student && student.student_id && student.team_id) {
      const result = await getRequests(undefined, student.team_id);
      //console.log(result);
      const transformedRequests = await transformRequests(result);
      if (transformedRequests instanceof FetchError) {
        if (transformedRequests.status === undefined) {
          console.error(transformedRequests.message);
        } else {
          console.error(
            `HTTP error ${transformedRequests.status}: ${transformedRequests.message}`
          );
        }
      } else {
        setTransformedRequests(transformedRequests);
      }
    }
  };

  useEffect(() => {
    if (user) {
      fetchRequests();
    }
  }, [user]);

  return (
    <div>
      <ContentCard
        title='New Request'
        description='Fill in the form below to submit a new parts request to your instructor(s). Part information may be autofilled based on matching part URLs.'
      >
        <div>
          <RequestForm selectedUser={user} onRequestSubmit={fetchRequests} />
        </div>
      </ContentCard>
      <ContentCard
        title='View Placed Requests'
        description={
          'View all the parts requests your team has placed to date.'
        }
      >
        <DataTable
          columns={defaultRequestColumns}
          data={transformedRequests}
          setData={setTransformedRequests}
        />
      </ContentCard>
    </div>
  );
};
