"use client";
import { useAppDispatch, useAppSelector } from "@/Redux/Hooks";
import { Button, Col, Form, FormGroup, Input, Label, Modal, ModalBody, Row, } from "reactstrap";
import { ChangeEvent, SyntheticEvent, useEffect, useState } from "react";
import { toast } from "react-toastify";
import DataService from "@/Config/Axios";
import { setLoading } from "@/Redux/Reducers/LayoutSlice";
import Link from "next/link";
import { NewUserInitialValue } from "@/Data/Application/Users";
import { useParams, useRouter } from "next/navigation";

const UsersUpdateForm = () => {
  const { i18LangStatus } = useAppSelector((state) => state.langSlice);
  const [isOpen, setIsOpen] = useState(false);
  const [tempPass, setTempPass] = useState("");
  const [data, setData] = useState<any>(NewUserInitialValue);
  const router = useRouter();
  const params = useParams();
  const [loading, setloading] = useState(false)

  const handleChange = (
    event: ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >
  ) => {
    const { name, value } = event.target;
    setData({ ...data, [name]: value });
    console.log(`User Details - ${name}: ${value}`);
  };
  const toggle = (password = "") => {
    setIsOpen(!isOpen);
    setTempPass(password);
  };

  const handleSubmit = async (event: SyntheticEvent) => {
    event.preventDefault();
    setloading(true);
    let payload = data;
    console.log(payload)
    try {
      const response = await DataService.post(`/users/${params.id}`, payload);
      console.log(response);
      // toggle(response.data.password);
      toast.success(response.data.message)
      router.push(`/${i18LangStatus}/users`)
      setloading(false);
    } catch (error: any) {
      console.log(error);
      setloading(false);
      toast.error(error?.response?.data?.message ?? "Something went wrong!");
    }
  };

  const callApi = async () => {
    setloading(true);
    try {
      const response = await DataService.get(`/users/${params.id}`);
      console.log(response.data.data);
      setData(response.data.data)
      setloading(false);
    } catch (error) {
      setloading(false);
      console.log(error);
    }
  };
  useEffect(() => {
    callApi();
  }, [])

  return (
    <Col sm={4} className="mx-auto">
      <Form className="theme-form" onSubmit={handleSubmit}>
        <Row>
          <Col >
            <FormGroup>
              <Label check>
                First Name<span className="text-danger">*</span>
              </Label>
              <Input
                onChange={handleChange}
                name="firstName"
                value={data?.firstName}
                type="text"
                className="form-control"
                required
              />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col >
            <FormGroup>
              <Label check>
                Last Name<span className="text-danger">*</span>
              </Label>
              <Input
                onChange={handleChange}
                name="lastName"
                value={data?.lastName}
                type="text"
                className="form-control"
                required
              />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col >
            <FormGroup>
              <Label check>
                Email Address
                <span className="text-danger">*</span>
              </Label>
              <Input
                onChange={handleChange}
                name="email"
                value={data?.email}
                className="form-control"
                type="text"
                required
              />
            </FormGroup>
          </Col>
        </Row>
        <Row>
          <Col >
            <FormGroup>
              <Label check>
                Status
                <span className="text-danger">*</span>
              </Label>
              <select
                onChange={handleChange}
                name="status"
                value={data?.status}
                className="form-control"
                required
              >
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
            </FormGroup>
          </Col>
        </Row>
        <Row className="mt-3">
          <Col className="d-flex justify-between">
            <Button
              disabled={loading}
              color="primary"
              type="submit"
              className="btn btn-primary  me-3"
            >
              Update
            </Button>
            <Link
              href={`/${i18LangStatus}/users`}
              className="btn btn-outline-primary"
            >
              Cancel
            </Link>
          </Col>
        </Row>
      </Form>
      <Modal isOpen={isOpen} toggle={() => toggle()}>
        <ModalBody>
          <div className=" d-flex flex-column">
            <h5>Temporary Password for this account is:</h5>
            <br />
            <div className="text-center w-100">
              <h4
                className="text-center"
                onClick={() => {
                  navigator.clipboard.writeText(tempPass);
                  toast.success("Text copied to clipboard!");
                }}
              >
                {tempPass}
              </h4>
            </div>
            <br />
            <div className="d-flex align-items-center justify-content-end w-100">
              <Button
                className="me-2"
                color="primary"
                onClick={() => {
                  navigator.clipboard.writeText(tempPass);
                  toast.success("Text copied to clipboard!");
                }}
              >
                Copy
              </Button>
              <Button
                color="link"
                className="btn btn-outline-primary"
                onClick={() => toggle()}
              >
                Close
              </Button>
            </div>
          </div>
        </ModalBody>
      </Modal>
    </Col>
  );
};

export default UsersUpdateForm;
