import React, { useEffect, useState } from "react";
import { getUser, patchUser } from "@/services/userService";
import { toast } from "react-toastify";
import './EditUserModal.css';
import CustomSelect from "@/components/common/CustomSelect";

const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    if (digits.length <= 3) return digits;
    if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6, 10)}`;
};

export default function EditUserModal({ show, onClose, userId }) {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const [form, setForm] = useState({
        full_name: "",
        phone_number: "",
        email: "",
        organization_name: "",
        address: "",
        status: "available"
    });

    useEffect(() => {
        if (userId && show) {
            loadUser();
        }
    }, [userId, show]);

    const loadUser = async () => {
        try {
            setLoading(true);
            const { data } = await getUser(userId);

            setForm({
                full_name: data.details?.full_name || "",
                // ✅ Format phone when loading existing data too
                phone_number: formatUSPhone(data.details?.phone_number || ""),
                email: data.email || "",
                organization_name: data.details?.organization_name || "",
                address: data.details?.address || "",
                status: data.details?.status || "available",
            });
        } catch {
            toast.error("Failed to load user");
        } finally {
            setLoading(false);
        }
    };

    const handleChange = (e) => {
        const { name, value } = e.target;

        // ✅ Format phone number while typing
        if (name === "phone_number") {
            setForm((prev) => ({ ...prev, phone_number: formatUSPhone(value) }));
            return;
        }

        setForm((prev) => ({ ...prev, [name]: value }));
    };

    const saveChanges = async () => {
        try {
            setSaving(true);

            const payload = {
                email: form.email,
                details: {
                    full_name: form.full_name,
                    // ✅ Strip formatting, send only raw digits
                    phone_number: form.phone_number.replace(/\D/g, ""),
                    address: form.address,
                    organization_name: form.organization_name,
                    status: form.status,
                }
            };

            await patchUser(userId, payload);

            toast.success("User updated successfully");
            onClose();
        } catch (err) {
            const details = err?.response?.data?.details;

            if (details) {
                Object.values(details).forEach(messages => {
                    if (Array.isArray(messages)) {
                        messages.forEach(msg => toast.error(msg));
                    }
                });
            } else {
                toast.error(err?.response?.data?.message || "Failed to update user");
            }
        } finally {
            setSaving(false);
        }
    };

    if (!show) return null;

    return (
        <div className="modal fade show" style={{ display: "block" }}>
            <div className="modal-dialog modal-lg modal-dialog-centered">
                <div className="modal-content editProfilepopup">
                    <div className="modal-header mb-3">
                        <div className="d-block">
                            <h5 className="modal-title">Edit User</h5>
                            <p>Update user information. The user's role can be changed separately.</p>
                        </div>
                        <button type="button" className="btn-close" onClick={onClose}></button>
                    </div>

                    <div className="modal-body">
                        {loading ? (
                            <p>Loading...</p>
                        ) : (
                            <div className="row">
                                <div className="col-md-6 mb-3">
                                    <label className="d-block text-start">
                                        Full Name <span className="text-danger">*</span>
                                    </label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        name="full_name"
                                        value={form.full_name}
                                        onChange={handleChange}
                                    />
                                </div>

                                <div className="col-md-6 mb-3">
                                    <label className="d-block text-start">Phone Number</label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        name="phone_number"
                                        // ✅ Displays formatted: (123) 456-7890
                                        value={form.phone_number}
                                        onChange={handleChange}
                                        placeholder="(123) 456-7890"
                                        maxLength={14} // (123) 456-7890 = 14 chars
                                    />
                                </div>

                                <div className="col-md-6 mb-3">
                                    <label className="d-block text-start">
                                        Email <span className="text-danger">*</span>
                                    </label>
                                    <input
                                        type="email"
                                        className="form-control"
                                        name="email"
                                        value={form.email}
                                        onChange={handleChange}
                                    />
                                </div>

                                <div className="col-md-6 mb-3">
                                    <label className="d-block text-start">Organization Name</label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        name="organization_name"
                                        value={form.organization_name}
                                        onChange={handleChange}
                                    />
                                </div>

                                <div className="col-md-12 mb-3">
                                    <label className="d-block text-start">Address</label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        name="address"
                                        value={form.address}
                                        onChange={handleChange}
                                    />
                                </div>

                                {/* <div className="col-lg-4 col-sm-6 text-start">
                                    <label className="d-block text-start">Select Status</label>
                                    <CustomSelect
                                        name="status"
                                        value={form.status}
                                        onChange={handleChange}
                                        placeholder="Select status"
                                        options={[
                                            { value: "available", label: "Available" },
                                            { value: "busy", label: "Busy" }
                                        ]}
                                    />
                                </div> */}

                                {/* <div className="col-md-6 mb-3">
                                    <label className="d-block text-start">Status</label>
                                    <input
                                        type="text"
                                        className="form-control"
                                        name="status"
                                        value={form.status
                                            ? form.status.charAt(0).toUpperCase() +
                                            form.status.slice(1).toLowerCase()
                                            : ""}
                                        onChange={handleChange}
                                        readOnly
                                    />
                                </div> */}


                            </div>
                        )}
                    </div>

                    <div className="modal-footer justify-content-between">
                        <button className="btn btn-light" onClick={onClose} disabled={saving}>
                            Cancel
                        </button>
                        <button className="btn btn-primary" onClick={saveChanges} disabled={saving}>
                            {saving ? "Saving..." : "Save Changes"}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}