import { useEffect, useState } from "react";
import { Feedback, FeedbackType } from "../../data";
import { AxiosResponse } from "axios";
import { axiosInstance } from "../../../axiosApi";
import Header2 from "../../components/Header2/Header2";
import ParticleBackground from "../../components/ParticleBackground/ParticleBackground";
import styled from "styled-components";
import { Form, Formik, Field, ErrorMessage } from "formik";
import * as Yup from 'yup';

// Styled Components
const PageContainer = styled.div`
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  color: ${({ theme }) => theme.colors.text};
  font-family: 'Inter', sans-serif;
  /* background-color: ${({ theme }) => theme.colors.background}; Removed to show particles */
`;

const ContentWrapper = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 6rem 2rem 2rem 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 5;

  &::-webkit-scrollbar {
    width: 8px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4px;
  }
`;

const GlassCard = styled.div`
  background: ${({ theme }) => theme.colors.cardBackground};
  backdrop-filter: blur(10px);
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 1rem;
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin-bottom: 2rem;
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
`;

const CardTitle = styled.h2`
  font-size: 1.8rem;
  margin-bottom: 1.5rem;
  color: ${({ theme }) => theme.colors.text};
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  padding-bottom: 1rem;
`;

const StyledInput = styled.input`
  width: 100%;
  background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'};
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  padding: 0.8rem;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;
  margin-bottom: 1rem;

  &:focus {
    background: rgba(255, 255, 255, 0.1);
    border-color: ${({ theme }) => theme.main};
    box-shadow: 0 0 10px ${({ theme }) => theme.main}33;
  }
`;

const StyledTextArea = styled.textarea`
  width: 100%;
  background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'};
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  padding: 0.8rem;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;
  min-height: 100px;
  resize: vertical;
  margin-bottom: 1rem;

  &:focus {
    background: rgba(255, 255, 255, 0.1);
    border-color: ${({ theme }) => theme.main};
    box-shadow: 0 0 10px ${({ theme }) => theme.main}33;
  }
`;

const StyledSelect = styled.select`
  width: 100%;
  background: ${({ theme }) => theme.darkMode ? 'rgba(255, 255, 255, 0.05)' : 'rgba(0, 0, 0, 0.05)'};
  border: 1px solid ${({ theme }) => theme.colors.cardBorder};
  border-radius: 0.5rem;
  padding: 0.8rem;
  color: ${({ theme }) => theme.colors.text};
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;
  margin-bottom: 1rem;
  appearance: none; /* Remove default arrow */
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='${({ theme }) => theme.darkMode ? 'white' : 'black'}' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 1rem center;
  background-size: 1em;

  &:focus {
    background-color: rgba(255, 255, 255, 0.1);
    border-color: ${({ theme }) => theme.main};
    box-shadow: 0 0 10px ${({ theme }) => theme.main}33;
  }

  option {
    background: ${({ theme }) => theme.colors.background};
    color: ${({ theme }) => theme.colors.text};
  }
`;

const StyledButton = styled.button`
  background: ${({ theme }) => theme.main};
  border: none;
  border-radius: 0.5rem;
  color: #fff;
  padding: 0.8rem 1.5rem;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  width: 100%;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px ${({ theme }) => theme.main}66;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
  }
`;

const StyledTable = styled.table`
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
`;

const Th = styled.th`
  text-align: left;
  padding: 1rem;
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  color: ${({ theme }) => theme.colors.text};
  opacity: 0.7;
  font-weight: 600;
`;

const Td = styled.td`
  padding: 1rem;
  border-bottom: 1px solid ${({ theme }) => theme.colors.cardBorder};
  color: ${({ theme }) => theme.colors.text};
`;

const categories = [
  { label: "Bug", value: "BUG" },
  { label: "Enhancement", value: "ENCHANCEMENT" },
  { label: "Other", value: "OTHER" }
];

const validationSchema = Yup.object().shape({
  text: Yup.string().min(1, "Need to have at least one character").required("This is required"),
  title: Yup.string().min(1, "Need to have at least one character").required("This is required"),
  category: Yup.string().required("Required")
});

type FeedbackSubmitValues = {
  text: string
  title: string
  category: string
}

type FeedbackTableCardProps = {
  feedbacks: Feedback[],
  setFeedbacks: React.Dispatch<React.SetStateAction<Feedback[]>>
}

const FeedbackTableCard = ({ feedbacks, setFeedbacks }: FeedbackTableCardProps): JSX.Element => {
  useEffect(() => {
    async function getFeedbacks() {
      try {
        const { data, }: AxiosResponse<FeedbackType[]> = await axiosInstance.get(`/feedbacks/`);
        setFeedbacks(data.map((item) => new Feedback({
          id: item.id,
          title: item.title,
          text: item.text,
          status: item.status,
          category: item.category,
        })))
      } catch (error) {
        console.log(error)
      }
    }
    getFeedbacks();
  }, [setFeedbacks])

  return (
    <GlassCard>
      <CardTitle>Feedback History</CardTitle>
      <div style={{ overflowX: 'auto' }}>
        <StyledTable>
          <thead>
            <tr>
              <Th>Title</Th>
              <Th>Category</Th>
              <Th>Text</Th>
              <Th>Status</Th>
            </tr>
          </thead>
          <tbody>
            {feedbacks.map((feedback, index) => (
              <tr key={index}>
                <Td>{feedback.title}</Td>
                <Td>{feedback.category}</Td>
                <Td>{feedback.text}</Td>
                <Td>{feedback.status}</Td>
              </tr>
            ))}
          </tbody>
        </StyledTable>
      </div>
    </GlassCard>
  )
}

const FeedbackSubmitCard = ({ feedbacks, setFeedbacks }: FeedbackTableCardProps) => {
  const handleFeedbackSubmit = async ({ text, title, category }: FeedbackSubmitValues, { resetForm }: any): Promise<void> => {
    try {
      await axiosInstance.post('/feedbacks/', {
        text: text,
        title: title,
        category: category
      })
      resetForm();
      setFeedbacks([...feedbacks, new Feedback({
        title: title,
        text: text,
        status: 'SUBMITTED',
        category: category,
      })])
    } catch {
      // put a message here
    }
  }
  return (
    <GlassCard>
      <CardTitle>Submit Feedback</CardTitle>
      <Formik
        initialValues={{
          text: '',
          title: '',
          category: '',
        }}
        onSubmit={handleFeedbackSubmit}
        validationSchema={validationSchema}
        validateOnMount>
        {(formik) =>
          <Form>
            <div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
              <div style={{ flex: '1 1 300px' }}>
                <Field
                  name='title'
                  as={StyledInput}
                  placeholder='Title'
                />
                <ErrorMessage name="title">
                  {msg => <div style={{ color: '#ff6b6b', fontSize: '0.9rem', marginTop: '-0.5rem', marginBottom: '1rem' }}>{msg}</div>}
                </ErrorMessage>
              </div>
              <div style={{ flex: '1 1 300px' }}>
                <Field
                  name="category"
                  as={StyledSelect}
                >
                  <option value="" label="Select Category" />
                  {categories.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Field>
                <ErrorMessage name="category">
                  {msg => <div style={{ color: '#ff6b6b', fontSize: '0.9rem', marginTop: '-0.5rem', marginBottom: '1rem' }}>{msg}</div>}
                </ErrorMessage>
              </div>
            </div>

            <Field
              name='text'
              as={StyledTextArea}
              placeholder='Describe your feedback...'
            />
            <ErrorMessage name="text">
              {msg => <div style={{ color: '#ff6b6b', fontSize: '0.9rem', marginTop: '-0.5rem', marginBottom: '1rem' }}>{msg}</div>}
            </ErrorMessage>

            <StyledButton
              type={'submit'}
              disabled={!formik.isValid}
            >
              Submit Feedback
            </StyledButton>
          </Form>
        }
      </Formik>
    </GlassCard>
  )
}

const FeedbackPageInner = (): JSX.Element => {
  const [feedbacks, setFeedbacks] = useState<Feedback[]>([]);
  return (
    <>
      <FeedbackSubmitCard setFeedbacks={setFeedbacks} feedbacks={feedbacks} />
      <FeedbackTableCard setFeedbacks={setFeedbacks} feedbacks={feedbacks} />
    </>
  )
}

const FeedbackPage2 = (): JSX.Element => {
  return (
    <PageContainer>
      <ParticleBackground />
      <Header2 />
      <ContentWrapper>
        <FeedbackPageInner />
      </ContentWrapper>
    </PageContainer>
  )
}

export default FeedbackPage2