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 { ConfigContext } from "../../Context/ConfigContext";
import { ContentLoader, NoRecords } from "../../Components/Shimmer";
import { formatDate } from "../../Components/GlobalFunctions";
import { handleDownloadOptions } from "../../Components/ExportData";

const Client = () => {
    const [profile_id, setprofile_id] = useState(0);
    const { apiURL, apiHeaderJson, apiHeaderFile } = useContext(ConfigContext);

    const [profile_name, setprofile_name] = useState("");
    const [profile_about, setprofile_about] = useState("");
    const [qid, setQId] = useState("");
    const [digitalSign, setDigitalSign] = useState(null);
    const [profile_address, setprofile_address] = useState("");
    const [profile_contact_number, setprofile_contact_number] = useState("");
    const [profile_whatsapp, setprofile_whatsapp] = useState("");
    const [profile_email, setprofile_email] = useState("");
    const [profilePicture, setProfilePicture] = useState(null);
    const [profile_category_id, setprofile_category_id] = useState("");
    const [category_rows, setCategoryRows] = useState([]);

    const [rows, setRows] = useState([]);
    const [next, setNext] = useState(false);
    const [prev, setPrev] = useState(false);
    const [page, setPage] = useState(1);
    const [limit] = useState(10);
    const [totalRecords, setTotalRecords] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [loadingList, setLoadingList] = useState(false);
    const [errors, setErrors] = useState({});

    useEffect(() => {
        fetchClientList();
        GetProductList()
    }, [page, limit]);

    const handleInputChange = (e, setter) => {
        setter(e.target.value);

        if (errors[e.target.name]) {
            setErrors((prev) => ({ ...prev, [e.target.name]: null }));
        }
    };

    const handleDigitalSignUpload = (e) => {
        const file = e.target.files[0];

        if (!file) return;

        if (!file.type.startsWith("image/")) {
            return Swal.fire("Error", "Please upload an image file", "error");
        }

        if (file.size > 2 * 1024 * 1024) {
            return Swal.fire("Error", "File size must be less than 2MB", "error");
        }

        setDigitalSign(file);
    };

    const handleProfilePictureUpload = (e) => {
        const file = e.target.files[0];

        if (file) {
            if (!file.type.match("image.*")) {
                Swal.fire({
                    title: "Error",
                    text: "Please upload an image file",
                    icon: "error",
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false,
                });
                return;
            }

            if (file.size > 2 * 1024 * 1024) {
                Swal.fire({
                    title: "Error",
                    text: "File size should be less than 2MB",
                    icon: "error",
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false,
                });
                return;
            }

            setProfilePicture(file);
        }
    };

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

        if (!profile_name.trim()) err.profile_name = "Client name is required";

        if (!profile_email.trim()) err.profile_email = "Email is required";
        else if (!/^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/.test(profile_email))
            err.profile_email = "Enter a valid email address";

        if (!profile_contact_number.trim()) err.profile_contact_number = "Contact number is required";

        if (!qid.trim()) err.qid = "QID is required";

        if (!profile_address.trim()) err.profile_address = "Address is required";

        if (!profile_about.trim()) err.profile_about = "About is required";

        if (!profile_whatsapp.trim()) err.profile_whatsapp = "Whatsapp is required";

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

    const GetInfo = async (id) => {
        try {
            const { data } = await axios.get(`${apiURL}api/profiles/${id}`, {
                headers: apiHeaderJson,
            });

            if (data.success) {
                const d = data.data;
                setprofile_id(d.profile_id);
                setprofile_name(d.profile_name);
                setprofile_email(d.profile_email);
                setQId(d.qid);
                setprofile_contact_number(d.profile_contact_number);
                setprofile_whatsapp(d.profile_whatsapp);
                setprofile_address(d.profile_address);
                setprofile_about(d.profile_about);
                setprofile_category_id(data.profile_category_id);
            }
        } catch (error) {
            console.error(error);
        }
    };

    const GetProductList = () => {
        const headers = apiHeaderJson;
        try {
            axios.get(`${apiURL}api/profile-categories`, {
                params: { pc_profile_type: 3 },
                headers,
            })
                .then((response) => {
                    const { data, success } = response.data;
                    if (success) {
                        setCategoryRows(
                            data

                                .map((row) => ({
                                    value: row.profile_category_id,
                                    label: row.pc_category_title,
                                }))
                        );
                    }
                });
        } catch (error) {
            console.log(error);
        }
    };

    const fetchClientList = async () => {
        setLoadingList(true);

        try {
            const { data } = await axios.get(`${apiURL}api/profiles`, {
                headers: apiHeaderJson,
                params: { profile_type: 3, page, limit },
            });

            if (data.success) {
                setRows(data.data);
                setNext(data.next);
                setPrev(data.prev);
                setTotalRecords(data.total_records);
                setTotalPages(data.total_pages);
            }
        } catch (error) {
            console.error(error);
        } finally {
            setLoadingList(false);
        }
    };

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

        try {
            const formData = new FormData();
            formData.append("profile_name", profile_name);
            formData.append("profile_about", profile_about);
            formData.append("profile_address", profile_address);
            formData.append("qid", qid);
            formData.append("profile_contact_number", profile_contact_number);
            formData.append("profile_whatsapp", profile_whatsapp);
            formData.append("profile_email", profile_email);

            if (digitalSign) formData.append("digital_signature", digitalSign);
            if (profilePicture) {
                formData.append("profile_picture", profilePicture);
            }

            formData.append("profile_category_id", "31");
            formData.append("pc_profile_type", "3");
            formData.append("profile_type", "3");
            formData.append("created_by", localStorage.getItem("user_id"));
            formData.append("created_date", formatDate());
            if (profile_id) formData.append("_method", "PUT");

            const url = `${apiURL}api/profiles${profile_id ? `/${profile_id}` : ""}`;
            // const method = profile_id ? "put" : "post";

            const { data } = await axios.post(url, formData, {
                headers: apiHeaderFile,
            });

            Swal.fire(data.success ? "Success" : "Failed", data.message, data.success ? "success" : "error");

            resetForm();
            fetchClientList();
        } catch (error) {
            if (error.response?.status === 422) {
                const msg = error.response.data.message[0];

                if (msg.includes("profile email has already been taken")) {
                    return Swal.fire("Error", msg, "error");
                }
            }

            Swal.fire("Error", "Unexpected error occurred!", "error");
        }
    };

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

        if (!confirm.isConfirmed) return;

        try {
            const { data } = await axios.delete(`${apiURL}api/profiles/${id}`, {
                headers: apiHeaderJson,
            });

            Swal.fire(data.success ? "Deleted" : "Failed", data.message, data.success ? "success" : "error");

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

    const handleDownload = (downloadType) => {
        const endpoint = `api/profiles`;

        const params = {
            profile_type: 3,      // 3 = client
            limit: totalRecords,  // download all records
            page,
        };

        const columns = [
            { header: "Client Name", width: 30 },
            { header: "Email", width: 35 },
            { header: "QID", width: 20 },
            { header: "Contact Number", width: 20 },
            { header: "WhatsApp Number", width: 20 },
            { header: "Address", width: 45 },
            { header: "About", width: 50 },
        ];

        const mapRow = (data) => ({
            "Client Name": data?.profile_name ?? "-",
            "Email": data?.profile_email ?? "-",
            "QID": data?.qid ?? "-",
            "Contact Number": data?.profile_contact_number ?? "-",
            "WhatsApp Number": data?.profile_whatsapp ?? "-",
            "Address": data?.profile_address ?? "-",
            "About": data?.profile_about ?? "-",
        });

        handleDownloadOptions(
            endpoint,
            params,
            columns,
            mapRow,
            downloadType,
            apiURL,
            apiHeaderJson
        );
    };


    const resetForm = () => {
        setprofile_id(0);
        setprofile_name("");
        setprofile_about("");
        setprofile_address("");
        setQId("");
        setprofile_contact_number("");
        setprofile_whatsapp("");
        setprofile_email("");
        setDigitalSign(null);
        setProfilePicture(null);
        setErrors({});
    };

    return (
        <div className="main-content">
            <div className="page-content">
                {!loadingList ? (
                    <div className="container-fluid">
                        <br />
                        <PageTitle title="Add Client" primary="Home" />

                        <div className="row">
                            {/* ---------------- LEFT FORM ---------------- */}
                            <div className="col-md-4">
                                <div className="card">
                                    <div className="card-header d-flex align-items-center" style={{ backgroundColor: "#000000" }}>
                                        <h4 className="card-title text-white mb-0 flex-grow-1">Client</h4>
                                    </div>
                                    <div className="card-body">
                                        <form className="row" onSubmit={handleSubmit}>
                                            {/* Inputs are unchanged, only cleaned */}
                                            {/* ---------------- Client Name ---------------- */}
                                            <div className="col-md-12">
                                                <label>Client Name</label>
                                                <input
                                                    type="text"
                                                    value={profile_name}
                                                    name="profile_name"
                                                    onChange={(e) => handleInputChange(e, setprofile_name)}
                                                    className={`form-control ${errors.profile_name ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter Client name"
                                                />
                                                {errors.profile_name && <div className="text-danger">{errors.profile_name}</div>}
                                            </div>

                                            {/* ---------------- Email ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>Email-Id</label>
                                                <input
                                                    type="text"
                                                    value={profile_email}
                                                    name="profile_email"
                                                    onChange={(e) => handleInputChange(e, setprofile_email)}
                                                    className={`form-control ${errors.profile_email ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter Email-Id"
                                                />
                                                {errors.profile_email && <div className="text-danger">{errors.profile_email}</div>}
                                            </div>

                                            {/* ---------------- QID ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>QID</label>
                                                <input
                                                    type="number"
                                                    value={qid}
                                                    name="qid"
                                                    onChange={(e) => handleInputChange(e, setQId)}
                                                    className={`form-control ${errors.qid ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter QID"
                                                />
                                                {errors.qid && <div className="text-danger">{errors.qid}</div>}
                                            </div>

                                            {/* ---------------- Contact ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>Contact Number</label>
                                                <input
                                                    type="number"
                                                    value={profile_contact_number}
                                                    name="profile_contact_number"
                                                    onChange={(e) => handleInputChange(e, setprofile_contact_number)}
                                                    className={`form-control ${errors.profile_contact_number ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter Contact Number"
                                                />
                                                {errors.profile_contact_number && (
                                                    <div className="text-danger">{errors.profile_contact_number}</div>
                                                )}
                                            </div>

                                            {/* ---------------- Whatsapp ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>WhatsApp Number</label>
                                                <input
                                                    type="number"
                                                    value={profile_whatsapp}
                                                    name="profile_whatsapp"
                                                    onChange={(e) => handleInputChange(e, setprofile_whatsapp)}
                                                    className={`form-control ${errors.profile_whatsapp ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter WhatsApp Number"
                                                />
                                                {errors.profile_whatsapp && (
                                                    <div className="text-danger">{errors.profile_whatsapp}</div>
                                                )}
                                            </div>

                                            {/* ---------------- Address ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>Address</label>
                                                <textarea
                                                    value={profile_address}
                                                    name="profile_address"
                                                    onChange={(e) => handleInputChange(e, setprofile_address)}
                                                    className={`form-control ${errors.profile_address ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter Address"
                                                />
                                                {errors.profile_address && (
                                                    <div className="text-danger">{errors.profile_address}</div>
                                                )}
                                            </div>

                                            {/* ---------------- About ---------------- */}
                                            <div className="col-md-12 mt-3">
                                                <label>About</label>
                                                <textarea
                                                    value={profile_about}
                                                    name="profile_about"
                                                    onChange={(e) => handleInputChange(e, setprofile_about)}
                                                    className={`form-control ${errors.profile_about ? "is-invalid" : ""}`}
                                                    placeholder="Please Enter About"
                                                />
                                                {errors.profile_about && (
                                                    <div className="text-danger">{errors.profile_about}</div>
                                                )}
                                            </div>

                                            {/* ---------------- Digital Sign ---------------- */}
                                            {/* <div className="col-md-12 mt-3">
                                                <label>Digital Sign</label>
                                                <input
                                                    type="file"
                                                    accept="image/*"
                                                    className="form-control"
                                                    onChange={handleDigitalSignUpload}
                                                />
                                            </div> */}
                                            <div className="col-md-12 mt-3">
                                                <label htmlFor="profile_picture">Logo Upload</label>
                                                <input
                                                    type="file"
                                                    id="profile_picture"
                                                    accept="image/*"
                                                    className="form-control"
                                                    onChange={handleProfilePictureUpload}
                                                />
                                            </div>

                                            {/* ---------------- Buttons ---------------- */}
                                            <div className="d-flex justify-content-between mt-4">
                                                {profile_id !== 0 ? (
                                                    <button type="button" className="btn btn-light btn-label" onClick={resetForm}>
                                                        <i className="ri-arrow-right-line label-icon fs-16 ms-2"></i> New
                                                    </button>
                                                ) : (
                                                    <div></div>
                                                )}

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

                            <div className="col-md-8">
                                <div className="card">
                                    <div className="card-header d-flex align-items-center" style={{ background: "#000000" }}>
                                        <h4 className="card-title text-white mb-0 flex-grow-1">Client List</h4>
                                    </div>

                                    <div className="card-body">
                                        <div className="row justify-content-end mb-4">
                                            <div className="col-md-3">

                                                <div className="dropdown">
                                                    <button type="button" className="btn btn-light btn-label waves-effect waves-light " id="dropdownMenuLink4" data-bs-toggle="dropdown" aria-expanded="true"
                                                    >
                                                        <i className="ri-download-2-line label-icon align-middle fs-16 me-2" />
                                                        Download Report
                                                    </button>
                                                    <ul className="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuLink4">
                                                        <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('print')}><i className="ri-printer-line me-2 align-middle text-muted" />Print</a>
                                                        </li>
                                                        <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('pdf')}><i className="ri-file-pdf-line me-2 align-middle text-muted" />PDF</a>
                                                            <li><a className="dropdown-item" style={{ cursor: "pointer" }} onClick={() => handleDownload('excel')}><i className="ri-file-excel-2-line me-2 align-middle text-muted" />Excel</a>
                                                            </li>

                                                        </li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="table-responsive table-card">
                                            <table className="table table-bordered table-striped table-nowrap">
                                                <thead className="table-light">
                                                    <tr>
                                                        <th className="text-center">Client Name</th>
                                                        <th className="text-center">Email-Id</th>
                                                        <th className="text-center">QID</th>
                                                        <th className="text-center">Contact</th>
                                                        <th className="text-center">WhatsApp</th>
                                                        <th className="text-center">Address</th>
                                                        <th className="text-center">About</th>
                                                        <th className="text-center">Logo</th>
                                                        <th className="text-center">Sign</th>
                                                        <th className="text-center">Action</th>
                                                    </tr>
                                                </thead>

                                                {rows.length ? (
                                                    <tbody>
                                                        {rows.map((row) => (
                                                            <tr key={row.profile_id}>
                                                                <td className="text-center">{row.profile_name}</td>
                                                                <td className="text-center">{row.profile_email}</td>
                                                                <td className="text-center">{row.qid}</td>
                                                                <td className="text-center">{row.profile_contact_number}</td>
                                                                <td className="text-center">{row.profile_whatsapp}</td>
                                                                <td className="text-center">{row.profile_address}</td>
                                                                <td className="text-center">{row.profile_about}</td>
                                                                <td className='text-center'>
                                                                    <img src={`${apiURL}public/profile_pictures/${row.digital_signature}`} width={35} alt="" />
                                                                </td>
                                                                <td className='text-center'>
                                                                    <img src={`${apiURL}api/profile-signature/${row.profile_picture}`} width={35} alt="" />
                                                                </td>
                                                                <td className="d-flex justify-content-between gap-1">
                                                                    <button
                                                                        className="btn btn-sm btn-outline-primary btn-icon"
                                                                        onClick={() => GetInfo(row.profile_id)}
                                                                    >
                                                                        <i className="ri-edit-box-line"></i>
                                                                    </button>

                                                                    <button
                                                                        className="btn btn-sm btn-outline-danger btn-icon"
                                                                        onClick={() => handleDelete(row.profile_id)}
                                                                    >
                                                                        <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>
                                                        <th colSpan={10}>
                                                            <div className="d-flex justify-content-between align-items-center">
                                                                {/* PREV */}
                                                                <button
                                                                    className="btn btn-warning btn-label"
                                                                    onClick={() => prev && setPage(page - 1)}
                                                                    disabled={!prev}
                                                                >
                                                                    <i className="ri-arrow-left-line label-icon me-2"></i> Previous
                                                                </button>

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

                                                                {/* Page Select */}
                                                                <select
                                                                    className="form-select w-auto"
                                                                    value={page}
                                                                    onChange={(e) => setPage(Number(e.target.value))}
                                                                >
                                                                    {Array.from({ length: totalPages }, (_, i) => (
                                                                        <option key={i + 1} value={i + 1}>
                                                                            {i + 1}
                                                                        </option>
                                                                    ))}
                                                                </select>

                                                                {/* NEXT */}
                                                                <button
                                                                    className="btn btn-primary btn-label"
                                                                    onClick={() => next && setPage(page + 1)}
                                                                    disabled={!next}
                                                                >
                                                                    Next <i className="ri-arrow-right-line label-icon ms-2"></i>
                                                                </button>
                                                            </div>
                                                        </th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                ) : (
                    <ContentLoader />
                )}
            </div>
        </div>
    );
};

export default Client;
