import React, { useEffect, useState } from 'react';
import { AxiosResponse } from 'axios';
import { axiosInstance } from '../../axiosApi';
import { Link } from 'react-router-dom';
import { FaqApi } from 'types';
import {
  Container,
  Typography,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Paper,
  Box,
} from '@mui/material';
import PageLoader from 'components/loading/PageLoader';
import IconifyIcon from 'components/base/IconifyIcon';

const FAQPage: React.FC = () => {
  const [faqs, setFaqs] = useState<FaqApi[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);

  useEffect(() => {
    const fetchFaqs = async () => {
      try {
        setLoading(true);
        const { data }: AxiosResponse<FaqApi[]> = await axiosInstance.get(`/support/faq/`);
        // Sort FAQs by order
        const sortedFaqs = data.sort((a, b) => a.order - b.order);
        setFaqs(sortedFaqs);
      } catch {
        setError(true);
      } finally {
        setLoading(false);
      }
    };
    fetchFaqs();
  }, []);

  if (loading) {
    return <PageLoader />;
  }

  if (error) {
    return (
      <Container>
        <Box sx={{ textAlign: 'center', mt: 4 }}>
          <Typography variant="h6" color="error">
            Failed to load FAQs. Please try again later.
          </Typography>
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="md">
      <Paper sx={{ my: 4, p: 3 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Frequently Asked Questions
        </Typography>
        <Typography variant="body1" paragraph>
          Most questions can be answered by looking through the frequently asked questions below. If
          you still have issues, you can <Link to="/support/manager">submit an issue</Link>.
        </Typography>
      </Paper>

      <Paper elevation={3} sx={{ p: 2 }}>
        {faqs.map((faq) => (
          <Accordion key={faq.order}>
            <AccordionSummary expandIcon={<IconifyIcon icon="mdi:chevron-down" />}>
              <Typography variant="h6">{faq.question}</Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Typography>{faq.answer}</Typography>
            </AccordionDetails>
          </Accordion>
        ))}
      </Paper>
    </Container>
  );
};

export default FAQPage;
