import React, { useState, useEffect, useContext } from 'react';
import PageTitle from "../../Components/PageTitle";
import { SubmitBtn } from "../../Components/InputElements";
import axios from 'axios';
import Swal from 'sweetalert2';
import Select from 'react-select';
import { ConfigContext } from '../../Context/ConfigContext';
import { ContentLoader, NoRecords } from "../../Components/Shimmer";
import { formatDate } from "../../Components/GlobalFunctions";

const Categories = () => {

  const { apiURL, apiHeaderJson } = useContext(ConfigContext);

  const [profile_category_id, setprofile_category_id] = useState(0);
  const [pc_category_title, setpc_category_title] = useState("");
  const [pc_profile_type, setpc_profile_type] = useState(null);

  const [rows, setRows] = useState([]);
  const [loadingList, setLoadingList] = useState(false);

  const [page, setPage] = useState(1);
  const [limit] = useState(10);
  const [totalRecords, setTotalRecords] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [next, setNext] = useState(false);
  const [prev, setPrev] = useState(false);

  const [errors, setErrors] = useState({});

  const typeOptions = [
    { value: "1", label: "Contractor" },
    { value: "2", label: "Consultant" },
    { value: "3", label: "Client" },
  ];

  useEffect(() => {
    loadList();
  }, [page]);

  const loadList = async () => {
    try {
      setLoadingList(true);
      const headers = apiHeaderJson;

      const response = await axios.get(`${apiURL}api/profile-categories`, {
        params: { limit, page },
        headers,
      });

      if (response.data.success) {
        const data = response.data;
        setRows(data.data);
        setNext(data.next);
        setPrev(data.prev);
        setTotalRecords(data.total_records);
        setTotalPages(data.total_pages);
      }

    } catch (error) {
      console.log(error);
    } finally {
      setLoadingList(false);
    }
  };

  const GetInfo = async (id) => {
    try {
      const headers = apiHeaderJson;
      const response = await axios.get(`${apiURL}api/profile-categories/${id}`, { headers });

      if (response.data.success) {
        const d = response.data.data;
        setprofile_category_id(d.profile_category_id);
        setpc_category_title(d.pc_category_title);
        setpc_profile_type(d.pc_profile_type);
      }

    } catch (error) {
      console.log(error);
    }
  };

  const validateForm = () => {
    const err = {};

    if (!pc_category_title.trim()) {
      err.pc_category_title = "Speciality Title is required";
    } else if (!/^[a-zA-Z0-9\s]+$/.test(pc_category_title)) {
      err.pc_category_title = "Speciality should not contain special characters";
    }

    if (!pc_profile_type) {
      err.pc_profile_type = "Please select Type";
    }

    setErrors(err);
    return Object.keys(err).length > 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (validateForm()) return;

    try {
      const headers = apiHeaderJson;

      const body = {
        pc_category_title,
        pc_profile_type: pc_profile_type,
        created_by: localStorage.getItem("user_id"),
        created_date: formatDate(),
      };

      const requestMethod = profile_category_id !== 0 ? "put" : "post";
      const url = `${apiURL}api/profile-categories${profile_category_id ? `/${profile_category_id}` : ""}`;

      const response = await axios[requestMethod](url, body, { headers });

      Swal.fire({
        title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
        text: profile_category_id ? "Speciality Updated Successfully" : "New Speciality Added Successfully",
        icon: response.data.success ? "success" : "error",
        timer: 2000,
        showConfirmButton: false,
      });

      if (response.data.success) {
        resetForm();
        loadList();
      }

    } catch (error) {
      console.log(error);
    }
  };

  const handleDelete = async (id) => {
    try {
      const result = await Swal.fire({
        title: "Are you sure?",
        text: "This action cannot be undone!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
      });

      if (result.isConfirmed) {
        const headers = apiHeaderJson;
        const response = await axios.delete(`${apiURL}api/profile-categories/${id}`, { headers });

        Swal.fire({
          title: `<strong>${response.data.success ? "Success" : "Failed"}</strong>`,
          text: response.data.message,
          icon: response.data.success ? "success" : "error",
          timer: 1000,
          showConfirmButton: false,
        });

        if (response.data.success) loadList();
      }

    } catch (error) {
      Swal.fire("Error", error.message, "error");
    }
  };

  const resetForm = () => {
    setprofile_category_id(0);
    setpc_category_title("");
    setpc_profile_type(null);
    setErrors({});
  };

  const handlePrev = () => prev && setPage(page - 1);
  const handleNext = () => next && setPage(page + 1);

  return (
    <div className="main-content">
      <div className="page-content">

        {!loadingList ? (
          <div className="container-fluid">
            <PageTitle title="Add Specialities" primary="Home" />

            <div className="row">
              <div className="col-md-4">
                <div className="card">
                  <div className="card-header" style={{ backgroundColor: "#000000" }}>
                    <h4 className="card-title flex-grow-1 text-white mb-0">Speciality</h4>
                  </div>

                  <div className="card-body">
                    <form onSubmit={handleSubmit}>

                      <div className="mt-3">
                        <label>Speciality Title:</label>
                        <input
                          type="text"
                          name="pc_category_title"
                          value={pc_category_title}
                          onChange={(e) => setpc_category_title(e.target.value)}
                          className={`form-control ${errors.pc_category_title ? "is-invalid" : ""}`}
                          placeholder="Please Enter Speciality"
                        />
                        {errors.pc_category_title && (
                          <small className="text-danger">{errors.pc_category_title}</small>
                        )}
                      </div>

                      {/* Type */}
                      <div className="mt-3">
                        <label>Type:</label>
                        <Select
                          options={typeOptions}
                          placeholder="Select Type"
                          value={typeOptions.find((opt) => opt.value === pc_profile_type) || null}
                          onChange={(selected) => setpc_profile_type(selected.value)}
                          className={errors.pc_profile_type ? "is-invalid" : ""}
                        />
                        {errors.pc_profile_type && (
                          <small className="text-danger">{errors.pc_profile_type}</small>
                        )}
                      </div>

                      <div className="d-flex justify-content-between mt-4">

                        {profile_category_id ? (
                          <button type="button" onClick={resetForm} className="btn btn-light">
                            New
                          </button>
                        ) : <div></div>}

                        <SubmitBtn
                          text={profile_category_id ? "Update" : "Save"}
                          icon="ri-save-line"
                          type="primary"
                        />
                      </div>

                    </form>
                  </div>
                </div>
              </div>

              {/* ---------------------- TABLE ---------------------- */}
              <div className="col-md-8">
                <div className="card">
                  <div className="card-header" style={{ backgroundColor: "#000000" }}>
                    <h4 className="card-title text-white mb-0">Specialities List</h4>
                  </div>

                  <div className="card-body">
                    <div className='table-responsive table-card'>
                      <table className="table table-bordered table-striped table-hover table-nowrap mb-0">
                        <thead className="table-light">
                          <tr>
                            <th width="10%">ID</th>
                            <th width="55%">Speciality</th>
                            <th width="20%">Type</th>
                            <th width="15%" className="text-center">Action</th>
                          </tr>
                        </thead>

                        {rows.length !== 0 ? (
                          <tbody>
                            {rows.map((row) => (
                              <tr key={row.profile_category_id}>
                                <td>{row.profile_category_id}</td>
                                <td>{row.pc_category_title}</td>
                                <td>
                                  {row.pc_profile_type === "1"
                                    ? <span className="badge bg-info">Contractor</span>
                                    : row.pc_profile_type === "2" ?
                                      <span className="badge bg-secondary">Consultant</span>
                                      : <span className="badge bg-primary">Client</span>
                                  }
                                </td>

                                <td className="text-center">
                                  <button
                                    onClick={() => GetInfo(row.profile_category_id)}
                                    className="btn btn-sm btn-outline-primary me-1"
                                  >
                                    <i className="ri-edit-box-line"></i>
                                  </button>

                                  <button
                                    onClick={() => handleDelete(row.profile_category_id)}
                                    className="btn btn-sm btn-outline-danger"
                                  >
                                    <i className="ri-delete-bin-line"></i>
                                  </button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        ) : (
                          <tbody>
                            <tr>
                              <td colSpan="10"><NoRecords /></td>
                            </tr>
                          </tbody>
                        )}

                        <tfoot className="table-light">
                          <tr>
                            <td colSpan={10}>
                              <div className="d-flex justify-content-between align-items-center">

                                <button
                                  disabled={!prev}
                                  onClick={handlePrev}
                                  className="btn btn-warning"
                                >
                                  Previous
                                </button>

                                <small>
                                  Total Records: {totalRecords} |
                                  Pages: {totalPages} |
                                  Current Page: {page}
                                </small>

                                <div className="col-md-2">
                                  <select className="form-select" onChange={(e) => setPage(Number(e.target.value))}>
                                    {Array.from({ length: totalPages }, (_, i) => (
                                      <option key={i + 1} value={i + 1}>{i + 1}</option>
                                    ))}
                                  </select>
                                </div>

                                <button
                                  disabled={!next}
                                  onClick={handleNext}
                                  className="btn btn-primary"
                                >
                                  Next
                                </button>

                              </div>
                            </td>
                          </tr>
                        </tfoot>

                      </table>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        ) : (
          <ContentLoader />
        )}
      </div>
    </div>
  );
};

export default Categories;
