import {
  useEditThreadMutation,
  useGetThreadsByIdQuery,
} from '@/lib/redux/services/Organizorflow/Dashboard.api';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';
import { Col, Container, Row, Spinner } from 'react-bootstrap';
import { useForm } from 'react-hook-form';
import toast from 'react-hot-toast';
import Progressbar from '@/components/Progressbar/progressbar';
import DashboardLayout from '@/components/Layouts/DashboardLayout';
import WebsiteLayout from '@/components/Layouts/WebsiteLayout';

const EditPollThread = () => {
  const [discussionThread, setDiscussionThread] = useState('');
  const [pollTitle, setPolTitle] = useState('');
  const [thumbnail, setThumbnail] = useState<File | null>(null);
  const [showInput, setShowInput] = useState(false);
  const [options, setOptions] = useState<string[]>([]);
  const { data: session }: any = useSession();
  const organizer_id = session?.user?._id;
  const router = useRouter();
  const handleChange = (index: any, event: any) => {
    const newOptions = [...options];
    newOptions[index] = event.target.value;
    setOptions(newOptions);
  };
  const { register, reset, handleSubmit, setValue } = useForm<any>({
    defaultValues: {
      organizationId: organizer_id,
      title: '',
      description: '',
      link: '',
      discussiontitle: '',
      pollTitle: '',
    },
  });
  const token = session?.user?.token;
  const skip = !token;
  const { id: threadId } = router.query;
  const [EditThread, { isLoading: loading }] = useEditThreadMutation();
  const {
    data: Getthreads,
    error,
    isLoading,
    refetch,
  } = useGetThreadsByIdQuery({ id: threadId, token }, { refetchOnMountOrArgChange: true, skip });

  const handleThreadEdit = async (data: any) => {
    const formData = new FormData();
    const feilds = {
      threadid: threadId,
      title: '',
      description: '',
      link: '',
      discussiontitle: '',
      pollTitle: pollTitle,
    };

    Object.entries(feilds).forEach(([key, value]) => formData.append(key, value as string));

    formData.append(`pollOptions`, JSON.stringify(options));

    try {
      const response: any = await EditThread({
        body: formData,
        token,
      }).unwrap();
      if (response?.status) {
        toast.success('Thread Updated Succesfully');
        reset();
        setThumbnail(null);
        router.push('/organizer/organizer-dashboard/comment/');
      }
    } catch (err: any) {
      const errorMessage = err?.data?.message || 'An error occurred. Please try again.';
      console.error(err);
      toast.error(errorMessage);
    }
  };

  useEffect(() => {
    if (Getthreads) {
      const { data }: any = Getthreads;
      if (data?.threadModel?.pollid) {
        setOptions(data?.threadModel?.pollid?.options);
      }
      if (data?.threadModel?.pollid) {
        setPolTitle(data?.threadModel?.pollid?.title);
      }
    }
  }, [Getthreads, setValue]);
  return (
    <WebsiteLayout>
      <Container fluid>
        <div
            style={{
              paddingInline: '70px',
              width: '400px',
            }}
          >
            <button
              type="button"
              className="btn btn-primary payment w-100 mb-3"
              onClick={() => router.back()}
            >
              Go Back
            </button>
          </div>
        <div className="dicussiondiv">
          

          {isLoading ? (
            <div className="spinner-container">
              <Spinner animation="border" className="custom-spinner" />
            </div>
          ) : (
            <>
              <div className="main-sect">
                <h2 className="heading text-dark">Edit Poll</h2>

                <Row>
                  <Col lg="12">
                    <div className="help-feedback">
                      <Row>
                        <Col lg={12}>
                          <div className="form-group">
                            <div className="icon-field">
                              <label htmlFor="">Title</label>
                              <input
                                type="text"
                                className="form-control"
                                placeholder="Food Relief"
                                value={pollTitle}
                                onChange={(e: any) => setPolTitle(e?.target.value)}
                              />
                            </div>
                          </div>
                          <div className="form-group">
                            <div className="icon-field">
                              <label htmlFor="">Option 1</label>
                              <input
                                type="text"
                                alt=""
                                className="form-control"
                                placeholder="Food Relief"
                                value={options[0] || ''}
                                onChange={(event) => handleChange(0, event)}
                              />
                            </div>
                          </div>
                          <div className="form-group">
                            <div className="icon-field">
                              <label htmlFor="">Option 2</label>
                              <input
                                alt=""
                                type="text"
                                className="form-control"
                                placeholder="Food Relief"
                                value={options[1] || ''}
                                onChange={(event) => handleChange(1, event)}
                              />
                            </div>
                          </div>

                          {showInput && (
                            <>
                              <div className="form-group">
                                <div className="icon-field">
                                  <label htmlFor="">Option 3</label>
                                  <input
                                    alt=""
                                    type="text"
                                    className="form-control"
                                    placeholder="Food Relief"
                                    value={options[2] || ''}
                                    onChange={(event) => handleChange(2, event)}
                                  />
                                </div>
                              </div>
                              <div className="form-group">
                                <div className="icon-field">
                                  <label htmlFor="">Option 4</label>
                                  <input
                                    alt=""
                                    type="text"
                                    className="form-control"
                                    placeholder="Food Relief"
                                    value={options[3] || ''}
                                    onChange={(event) => handleChange(3, event)}
                                  />
                                </div>
                              </div>
                            </>
                          )}
                          <div className="option-btn">
                            <button onClick={() => setShowInput((prev) => !prev)} type="button">
                              <img src={'/images/sidbar-icon/add-square.svg'} alt="" />{' '}
                              {showInput ? `less options` : `Add More Option`}{' '}
                            </button>
                          </div>

                          <div className="form-group">
                            <div className="icon-field">
                              {Getthreads?.data?.responseOfPoll?.map((result: any, index: any) =>
                                result?.result?.map((e: any, index: any) => {
                                  return (
                                    <div className="progressmain" key={index}>
                                      <Progressbar
                                        percentage={e?.percentage}
                                        label={`${e?.percentage.toFixed(2)}%  `}
                                      />
                                    </div>
                                  );
                                })
                              )}
                            </div>
                          </div>

                          <div className="thread-btn">
                            <button
                              className="btn btn-primary mt-3 w-100"
                              type="button"
                              onClick={handleThreadEdit}
                            >
                            {loading ? <Spinner size="sm" /> : 'Edit Now'}
                            </button>
                          </div>
                        </Col>
                      </Row>
                    </div>
                  </Col>
                </Row>
              </div>
            </>
          )}
        </div>
      </Container>
    </WebsiteLayout>
  );
};

export default EditPollThread;
