/* eslint-disable @next/next/no-img-element */
import WebsiteLayout from '@/components/Layouts/WebsiteLayout';
import {
  useGetProfilepersonalizedQuery,
  useGetpersonalizedQuery,
} from '@/lib/redux/services/Organizorflow/Dashboard.api';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
import { Col, Container, Row, Spinner } from 'react-bootstrap';
import { useEditAnswersMutation } from '@/lib/redux/services/Userflow/UserDashboard.api';
import { useEffect, useState } from 'react';
import toast from 'react-hot-toast';

export default function CreateProfile() {
  const { data: session }: any = useSession();
  const token = session?.user?.token;
  const router = useRouter();
  const flowtype = session?.user?.flowtype;

  const { data: profileData, isLoading } = useGetProfilepersonalizedQuery({ token });
 
  const [HandleEditAnswers, { isLoading: EditLoading }] = useEditAnswersMutation();

  const [answers, setAnswers] = useState<{ questionId: string; givenAnswer: string[] }[]>([]);

  useEffect(() => {
    if (profileData?.data) {
      const mappedAnswers = profileData.data.flatMap((item: any) =>
        item.answers.map((ans: any) => ({
          questionId: ans.questionId._id,
          givenAnswer: ans.givenAnswer || [],
        }))
      );
      setAnswers(mappedAnswers);
    }
  }, [profileData]);

  const handleOptionChange = (questionId: string, value: string, isMultiple: boolean) => {
    setAnswers((prev) => {
      const existing = prev.find((ans) => ans.questionId === questionId);
      if (existing) {
        return prev.map((ans) => {
          if (ans.questionId === questionId) {
            let updated;
            if (isMultiple) {
              updated = ans.givenAnswer.includes(value)
                ? ans.givenAnswer.filter((v) => v !== value)
                : [...ans.givenAnswer, value];
            } else {
              updated = [value];
            }
            return { ...ans, givenAnswer: updated };
          }
          return ans;
        });
      } else {
        return [...prev, { questionId, givenAnswer: [value] }];
      }
    });
  };

  const handleTextChange = (questionId: string, value: string) => {
    setAnswers((prev) => {
      const existing = prev.find((ans) => ans.questionId === questionId);
      if (existing) {
        return prev.map((ans) =>
          ans.questionId === questionId ? { ...ans, givenAnswer: [value] } : ans
        );
      } else {
        return [...prev, { questionId, givenAnswer: [value] }];
      }
    });
  };

  const handleSubmit = async () => {
    try {
      const payload = { answers };
      const res = await HandleEditAnswers({ body: payload, token }).unwrap();
      if (res?.status) {
        router.push('/organizer/organizer-profile/persnalized-question');
        toast?.success('Answers Updated Succesfully');
      }
    } catch (error: any) {
      console.error('Error submitting answers:', error);
      toast?.error(error?.data?.message);
    }
  };


  return (
    <WebsiteLayout>
      <div className="edit-profile personal-sec">
        <Container fluid>
          <div className="main-sect">
            <Row className="mt-5">
              <Col lg="4">
                <button
                  type="button"
                  className="btn btn-primary payment w-50"
                  onClick={() => router.back()}
                >
                  Go Back
                </button>
              </Col>
              <Col lg="4">
                <div className="direct-screen-hed">
                  <h2 className="heading mb-0">Edit Personalized Questions</h2>
                </div>
              </Col>
              <Col lg="4"></Col>
            </Row>

            <Row className="justify-content-center mt-4">
              <Col lg={10}>
                <Row>
                  {profileData?.data?.map((item: any) =>
                    item.answers.map((data: any, index: number) => {
                      const question = data.questionId;
                      const selectedAnswers =
                        answers.find((ans) => ans.questionId === question._id)?.givenAnswer || [];
                      const isMultiple = question.answerSelectionType === 'multiple';

                      return (
                        <Col lg="6" key={index}>
                          <div
                            className="persnalize"
                            style={{
                              display: 'flex',
                              flexDirection: 'column',
                              height: '300px',
                              border: '1px solid #ddd',
                              padding: '15px',
                              borderRadius: '8px',
                              background: '#fff',
                            }}
                          >
                            <h4>{question?.questiontext}</h4>
                            <div className="form-group" style={{ flex: 1, overflowY: 'auto' }}>
                              {question?.questiontype === 'radio' ? (
                                <>
                                  {question?.options?.map((option: string, idx: number) => (
                                    <div className="form-group" key={idx}>
                                      <input
                                        type={isMultiple ? 'checkbox' : 'radio'}
                                        id={`option-${index}-${idx}`}
                                        name={`question-${question._id}`}
                                        value={option}
                                        checked={selectedAnswers.includes(option)}
                                        onChange={(e) =>
                                          handleOptionChange(
                                            question._id,
                                            e.target.value,
                                            isMultiple
                                          )
                                        }
                                        style={{
                                          appearance: 'none',
                                          WebkitAppearance: 'none',
                                          MozAppearance: 'none',
                                          width: '18px',
                                          height: '18px',
                                          border: '2px solid #04a5a0',
                                          borderRadius: isMultiple ? '4px' : '50%',
                                          outline: 'none',
                                          cursor: 'pointer',
                                          position: 'relative',
                                          marginRight: '8px',
                                          backgroundColor: selectedAnswers.includes(option)
                                            ? '#04a5a0'
                                            : '#fff',
                                          transition: 'background-color 0.2s ease-in-out',
                                        }}
                                      />
                                      <label>{option}</label>
                                    </div>
                                  ))}
                                </>
                              ) : (
                                <div className="icon-field">
                                  <label htmlFor="">Answer</label>
                                  <textarea
                                    className="form-control"
                                    placeholder="Enter Your Answer here"
                                    style={{ width: '100%', height: '170px' }}
                                    value={selectedAnswers[0] || ''}
                                    onChange={(e) => handleTextChange(question._id, e.target.value)}
                                  />
                                </div>
                              )}
                            </div>
                          </div>
                        </Col>
                      );
                    })
                  )}
                </Row>

                <div className="form-group mt-4 text-center">
                  <button type="button" className="btn btn-primary w-50" onClick={handleSubmit}>
                    {EditLoading ? <Spinner size="sm" /> : 'Save'}
                  </button>
                </div>
              </Col>
            </Row>
          </div>
        </Container>
      </div>
    </WebsiteLayout>
  );
}
