"use client";
import { useAppSelector } from "@/Redux/Hooks";
import { useRouter } from "next/navigation";
import Link from "next/link";
import {
  Button,
  Card,
  CardBody,
  Col,
  Container,
  Form,
  FormGroup,
  Input,
  Label,
  Row,
} from "reactstrap";
import { CreateSupport, Support } from "@/Constant";
import { Dropzone, ExtFile, FileMosaic } from "@dropzone-ui/react";
import { ChangeEvent, SyntheticEvent, useEffect, useState } from "react";
import { toast } from "react-toastify";
import DataService from "@/Config/Axios";
import { AdminSupportEmailTemplate, UserSupportEmailTemplate } from "@/utils/email";
import logo from '../../../../../../public/assets/images/logo/04.png'
import dynamic from "next/dynamic";

const Breadcrumbs = dynamic(() => import("@/CommonComponent/Breadcrumbs"), { ssr: false })

const Page = () => {
  const router = useRouter();
  const { i18LangStatus } = useAppSelector((state) => state.langSlice);
  const [files, setFiles] = useState<ExtFile[]>([]);
  const [file, setFile] = useState<any>({});
  const [data, setData] = useState<any>({})
  const [user, setUser] = useState<any>()
  const [userLoggedIn, setuserLoggedIn] = useState(JSON.parse(localStorage.getItem('user') ?? ""))
  const handleSubmit = async (e: SyntheticEvent) => {
    if (data.message && data.subject) {

    }
    else {
      toast.error("Please fill out the fields")
      return
    }
    e.preventDefault()
    let formData = new FormData();
    formData.append('message', data.message)
    formData.append('subject', data.subject)
    formData.append('userId', data.userId)
    if (file) {
      formData.append('attachment', file)
    }
    setData({ ...data, userId: userLoggedIn._id })
    let emailVars = {
      address: "",
      name: user?.name,
      ticketNumber: "",
      ticketSubject: "",
      ticketDescription: "",
      createdDate: new Date(),
      companyName: user?.companyName,
      logo: logo
    }

    try {
      const response = await DataService.post('/support/create', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
      if (!response.data.status) {
        return;
      }
      emailVars.ticketNumber = response.data.data.ticketNumber;
      emailVars.ticketSubject = response.data.data.subject;
      emailVars.ticketDescription = response.data.data.message;
      console.log(emailVars)
      const adminTemplateHtml = AdminSupportEmailTemplate(emailVars)
      const userTemplateHtml = UserSupportEmailTemplate(emailVars)
      await DataService.post('/support/email/admin', { subject: response.data.data.subject, content: adminTemplateHtml })
      await DataService.post('/support/email/user', { email: user?.email, subject: response.data.data.subject, content: userTemplateHtml })
      if (response.data.status) {
        toast.success(response.data.message)
      } else {
        toast.error(response.data.message)
      }
    } catch (error: any) {
      toast.error(error?.response?.data?.message ?? "Something went wrong!");
    }
    router.push(`/${i18LangStatus}/support_tickets`);
  };
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setData({ ...data, [name]: value })
  }

  const callApi = async () => {
    try {
      const response = await DataService.post(`/admins/${userLoggedIn._id}`);
      if (response.data.status) {
        setUser(response.data.data)
      }
    } catch (error) {

    }
  }
  useEffect(() => {
    setData({ ...data, userId: userLoggedIn._id })
    callApi()
  }, [])
  console.log(data)
  return (
    <>
      <Breadcrumbs pageTitle={CreateSupport} parent={Support} />
      <Container fluid>
        <Row>
          <Col sm="12">
            <Card>
              <CardBody>
                <Form className="theme-form" onSubmit={handleSubmit}>
                  <Row>
                    <Col sm="12">
                      <FormGroup>
                        <Label check>Subject</Label>
                        <Input
                          onChange={handleChange}
                          name="subject"
                          type="text"
                          className="form-control"
                          required
                        />
                      </FormGroup>
                    </Col>
                  </Row>
                  <Row>
                    <Col sm="12">
                      <FormGroup>
                        <Label check>Message</Label>
                        <Input
                          onChange={handleChange}
                          rows="5"
                          name="message"
                          className="form-control"
                          type="textarea"
                          placeholder=""
                          required
                        />
                      </FormGroup>
                    </Col>
                  </Row>
                  <Row>
                    <Col>
                      <FormGroup>
                        <Label check>Upload Attachments</Label>
                        <Input type="file" onChange={(e: any) => setFile(e.target.files[0])} />
                        {/* <Dropzone
                          onChange={updateFiles}
                          value={files}
                          maxFiles={1}
                          header={false}
                          footer={false}
                          minHeight="80px"
                          label="Drag'n drop files here or click to Browse"
                        >
                          {files.map((file: ExtFile) => (
                            <FileMosaic
                              key={file.id}
                              {...file}
                              onDelete={removeFile}
                              info={true}
                            />
                          ))}
                          {files.length === 0 && (
                            <div className="dz-message needsclick">
                              <i className="icon-cloud-up txt-primary"></i>
                              <h6>Drop files here or click to upload.</h6>
                            </div>
                          )}
                        </Dropzone> */}
                      </FormGroup>
                    </Col>
                  </Row>
                  <Label check>Support Documentation:</Label>
                  <Row className="align-items-center">
                    <Col sm="8">
                      <FormGroup
                        className="d-flex align-items-center"
                        style={{ gap: "2rem" }}
                      >
                        <Input
                          type="select"
                          className="form-control form-select"
                        >
                          <option value="">Create Customer</option>
                          <option value="">Input Invoice</option>
                          <option value="">Create reminder session</option>
                          <option value="">Create Receipt/Cancel</option>
                          <option value="">
                            Create session to remind all Invoices
                          </option>
                        </Input>
                        <Link href={"#"} className="">
                          Download
                        </Link>
                      </FormGroup>
                    </Col>
                    <Col sm={2}>
                      <div className="text-end"></div>
                    </Col>
                  </Row>
                  <Row>
                    <Col>
                      <div className="text-end">
                        <Button
                          type="submit"
                          color="primary"
                          className="me-3"
                        >
                          Add
                        </Button>
                        <Link
                          href={`/${i18LangStatus}/support_tickets`}
                          className="btn btn-outline-primary"
                        >
                          Cancel
                        </Link>
                      </div>
                    </Col>
                  </Row>
                </Form>
              </CardBody>
            </Card>
          </Col>
        </Row>
      </Container>
    </>
  );
};

export default Page;
