

import React, { useState, useEffect } from "react";
import axios from "axios";
import { useLocation, useNavigate } from "react-router-dom";
import {
  Container,
  Row,
  Col,
  Table,
  Button,
  Dropdown,
  Form,
  Pagination,
} from "react-bootstrap";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTrash, faWrench, faPlus } from "@fortawesome/free-solid-svg-icons";
import Spinner from "../../../UIComponants/Spinner";
import "../CSS/CSS/CommonStyle.css";
import { BsJournals } from "react-icons/bs";
import { fetchForms, deleteForm } from "../../../APIServices/DynamicFormAPI";
import { toast } from "react-toastify";

const DynamicForm2 = () => {
  const [forms, setForms] = useState([]);
  const [error, setError] = useState(null);
  const [filteredForms, setFilteredForms] = useState([]);
  const [visibleColumns, setVisibleColumns] = useState({
    formName: true,
    formDescription: true,
    relatedTo: true,
    pageEvent: true,
    buttonCaption: true,
    goToForm: true,
  });
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const location = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setLoading(false);
    }, 3000);
  }, []);

  useEffect(() => {
    if (location.state && location.state.formData) {
      setForms((prevForms) =>
        Array.isArray(prevForms)
          ? [...prevForms, location.state.formData]
          : [location.state.formData]
      );
    } else {
      fetchForms();
    }
  }, [location.state]);

  useEffect(() => {
    // Check if forms is an array before attempting to filter it
    if (Array.isArray(forms)) {
      const filtered = forms.filter((form) =>
        Object.values(form).some(
          (value) =>
            typeof value === "string" &&
            value.toLowerCase().includes(searchQuery.toLowerCase())
        )
      );
      setFilteredForms(filtered);
    }
  }, [searchQuery, forms]);

  useEffect(() => {
    // loadForms();
    console.log("useEffect for loadForms triggered");
    if (location.state && location.state.formData) {
      console.log(
        "Adding form data from location state:",
        location.state.formData
      );
      setForms((prevForms) =>
        Array.isArray(prevForms)
          ? [...prevForms, location.state.formData]
          : [location.state.formData]
      );
    }

    console.log("Calling loadForms()");
    loadForms();
  }, [location.state]);


  const loadForms = async () => {
    console.log("loadForms function is called");
    try {
      const formData = await fetchForms();
      console.log("data fetching on form", formData);
      toast.success("Successfully fetched data!");
      setForms(formData);
    } catch (error) {
      setError("error fetching data ", error.message);
      toast.error("Error fetching data!");
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (formId) => {
    console.log("Deleting data with ID:", formId);

    if (!formId) {
      toast.error("Invalid ID. Unable to delete.");
      return;
    }
    try {
      // const apiUrl = `${process.env.REACT_APP_API_URL}/api/form_setup/${id}`;
      // const token = localStorage.getItem("authToken");
      // await axios.delete(apiUrl, {
      //   headers: {
      //     "Content-Type": "application/json",
      //     Authorization: `Bearer ${token}`,
      //   },
      // });
      const deleteFormData = await deleteForm(formId);
      toast.success("Successfully deleted data!");
      console.log("Deleted data:", deleteFormData);
      setForms((prevForms) => {
        return prevForms.filter((form) => {
          return form.id !== formId;
        });
      });
    } catch (error) {
      console.error("Error deleting data:", error);
      toast.error("Error deleting data!");
    }
  };

  const handleBuild = async (id) => {
    try {
      const apiUrl = `${process.env.REACT_APP_API_URL}api/dynamic_form_build`;
      const token = localStorage.getItem("authToken");
      await axios.post(
        apiUrl,
        { id },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        }
      );
    } catch (error) {
      console.error("Error building form:", error);
    }
  };

  const handleAdd = () => {
    navigate("/admin/dynamic-form-add");
  };

  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({ ...prev, [column]: !prev[column] }));
  };

  const handleSearchChange = (event) => {
    setSearchQuery(event.target.value);
  };

  const handleRecordsPerPageChange = (records) => {
    setRecordsPerPage(records);
    setCurrentPage(1); // Reset to the first page
  };

  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  const totalPages = Math.ceil(filteredForms.length / recordsPerPage);
  const currentRecords = filteredForms.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

  return (
    <div style={{ marginTop: "11rem" }}>
      {loading ? (
        <Spinner />
      ) : (
        <Container
          fluid
          style={{ maxWidth: "95%", margin: "0 auto", overflowX: "hidden" }}
        >
          <Row>
            <Col>
              <h1 className="title_main">Dynamic Form</h1>
            </Col>
          </Row>
          <Row className="mb-3">
            <Col md={6}>
              <Form.Control
                type="text"
                placeholder="Search forms..."
                value={searchQuery}
                onChange={handleSearchChange}
              />
            </Col>
            <Col md={6} className="text-end">
              <Button
                color="primary"
                onClick={handleAdd}
                className="custom_button"
              >
                <FontAwesomeIcon icon={faPlus} /> Add
              </Button>
            </Col>
          </Row>
          <Row>
            <Col>
              <div className="table-wrapper">
                <Table
                  striped
                  hover
                  responsive
                  className="table-flush shadow-sm"
                  align="middle"
                >
                  <thead className="table-light custom_header">
                    <tr>
                      {visibleColumns.formName && <th>Form Name</th>}
                      {visibleColumns.formDescription && (
                        <th>Form Description</th>
                      )}
                      {visibleColumns.relatedTo && <th>Related To</th>}
                      {visibleColumns.pageEvent && <th>Page Event</th>}
                      {visibleColumns.buttonCaption && <th>Button Caption</th>}
                      {visibleColumns.goToForm && <th>Go To Form</th>}
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {currentRecords.length > 0 ? (
                      currentRecords.map((form, index) => (
                        <tr key={index}>
                          {visibleColumns.formName && <td>{form.formName}</td>}
                          {visibleColumns.formDescription && (
                            <td>{form.formDescription}</td>
                          )}
                          {visibleColumns.relatedTo && (
                            <td>{form.relatedTo}</td>
                          )}
                          {visibleColumns.pageEvent && (
                            <td>{form.pageEvent}</td>
                          )}
                          {visibleColumns.buttonCaption && (
                            <td>{form.buttonCaption}</td>
                          )}
                          {visibleColumns.goToForm && <td>{form.goToForm}</td>}
                          <td>
                            <FontAwesomeIcon
                              icon={faWrench}
                              color="blue"
                              style={{ cursor: "pointer" }}
                              onClick={() => handleBuild(form.id)}
                            />
                            <FontAwesomeIcon
                              icon={faTrash}
                              color="red"
                              style={{ cursor: "pointer", marginLeft: "10px" }}
                              onClick={() => {
                                if (!form.id) {
                                  console.error("Invalid form ID:", form);
                                  toast.error("Cannot delete: Invalid ID!");
                                  return;
                                }
                                handleDelete(form.form_id);
                              }}
                            />
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan="8" className="text-center text-muted">
                          No forms available. Click "Add" to create a new one.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </Table>
              </div>
            </Col>
          </Row>
          <Row className="mt-4">
            <Col md={6} className="d-flex justify-content-start">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button"
                >
                  Manage Columns
                </Dropdown.Toggle>
                <Dropdown.Menu>
                  {Object.keys(visibleColumns).map((column) => (
                    <Dropdown.Item
                      key={column}
                      onClick={() => toggleColumn(column)}
                    >
                      <Form.Check
                        type="checkbox"
                        label={column}
                        checked={visibleColumns[column]}
                        readOnly
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>
            <Col md={6} className="d-flex justify-content-end">
              <Dropdown>
                <Dropdown.Toggle
                  variant="outline-primary"
                  className="custom_manage_column_button px-4 py-2 border-2 rounded-3 shadow-sm"
                  id="dropdown-custom-components"
                >
                  <BsJournals />
                </Dropdown.Toggle>
                <Dropdown.Menu
                  className="border-0 rounded-3 shadow-lg"
                  align="end"
                >
                  {[1, 5, 10, 20, 50].map((number) => (
                    <Dropdown.Item
                      key={number}
                      onClick={() => handleRecordsPerPageChange(number)}
                      className="text-dark d-flex justify-content-between align-items-center"
                    >
                      <span>{number}</span>
                      <i
                        className="fa fa-check-circle"
                        style={{
                          display:
                            recordsPerPage === number ? "inline" : "none",
                        }}
                      />
                    </Dropdown.Item>
                  ))}
                </Dropdown.Menu>
              </Dropdown>
            </Col>
          </Row>
          <Pagination className="pagination justify-content-center mt-4">
            <Pagination.First
              disabled={currentPage === 1}
              onClick={() => handlePageChange(1)}
            />
            <Pagination.Prev
              disabled={currentPage === 1}
              onClick={() => handlePageChange(currentPage - 1)}
            />
            {[...Array(totalPages)].map((_, index) => (
              <Pagination.Item
                key={index + 1}
                active={currentPage === index + 1}
                onClick={() => handlePageChange(index + 1)}
              >
                {index + 1}
              </Pagination.Item>
            ))}
            <Pagination.Next
              disabled={currentPage === totalPages}
              onClick={() => handlePageChange(currentPage + 1)}
            />
            <Pagination.Last
              disabled={currentPage === totalPages}
              onClick={() => handlePageChange(totalPages)}
            />
          </Pagination>
        </Container>
      )}
    </div>
  );
};

export default DynamicForm2;
