import React, { useEffect, useState, useRef, useContext } from "react";
import { useParams } from "react-router-dom";
import "./ContractsDetail.css";
import { langContext } from "../../context/LenguageContext";

export default function ContractsDetail() {
    const { id } = useParams();
    const { lang } = useContext(langContext);

    const [form, setForm] = useState({
        name_employee: "",
        id_position_emp: "",
        id_area_emp: "",
        start_contract: "",
        end_contract: "",
        status_contract: "",
        new_daily_pay: "",
        uniforms: [],
    });

    const [positions, setPositions] = useState([]);
    const [areas, setAreas] = useState([]);
    const [uniforms, setUniforms] = useState([]);
    const [selectedUniforms, setSelectedUniforms] = useState([]);

    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [successMsg, setSuccessMsg] = useState("");
    const initialFormRef = useRef(null);

    // 🧭 Formatear fecha a yyyy-MM-dd
    const formatDate = (iso) => {
        if (!iso) return "";
        const d = new Date(iso);
        return d.toISOString().split("T")[0];
    };

    //Cargar áreas, uniformes y positions
    useEffect(() => {
        const baseApiUrl = import.meta.env.VITE_API_BASE_URL;

        const fetchOptions = async () => {
            try {
                // Primer fetch (igual que antes)
                const res = await fetch(`${baseApiUrl}/expenses/getinfo`);
                const data = await res.json();

                console.log("DEBUG: expenses/getinfo ->", data);

                setUniforms(data.uniforms || []);
                setAreas(data.areas || []);

                // Segundo fetch para positions
                const resPositions = await fetch(`${baseApiUrl}/contracts/positions`);
                const dataPositions = await resPositions.json();
                console.log("DEBUG: contracts/positions ->", dataPositions);

                setPositions(dataPositions.data || []);
            } catch (err) {
                console.error("❌ Error loading options:", err);
            }
        };

        fetchOptions();
    }, []);


    //Cargar contrato específico
    useEffect(() => {
        const baseApiUrl = import.meta.env.VITE_API_BASE_URL;

        const fetchContract = async () => {
            try {
                const response = await fetch(`${baseApiUrl}/contracts/getinfocontract/${id}`);
                const resData = await response.json();

                if (!resData.data || resData.data.length === 0) {
                    setError("Contract not found");
                    setLoading(false);
                    return;
                }

                const c = resData.data[0];

                // 🔍 Mapeo más flexible: busca coincidencias por nombre
                const positionMatch = positions.find(
                    (p) =>
                        p.name_position?.toLowerCase().trim() ===
                        c.position_employee?.toLowerCase().trim()
                );

                const areaMatch = areas.find(
                    (a) => a.name?.toLowerCase().trim() === c.area_employee?.toLowerCase().trim()
                );

                const loaded = {
                    name_employee: c.name_employee || "",
                    id_position_emp: positionMatch?.id_position || "",
                    id_area_emp: areaMatch?.id_area || areaMatch?.id || "",
                    start_contract: formatDate(c.contract_start),
                    end_contract: formatDate(c.contract_end),
                    status_contract: c.status_contract,
                    new_daily_pay: c.daily_pay || "",
                    uniforms: [],
                };

                setForm(loaded);
                initialFormRef.current = loaded;
                setLoading(false);
            } catch (err) {
                console.error("❌ Error loading contract:", err);
                setError("Contract could not be loaded");
                setLoading(false);
            }
        };

        fetchContract();
    }, [id, positions, areas]);



    // 🔹 Manejadores de cambios
    const handleChange = (e) => {
        const { name, value } = e.target;
        setForm((prev) => ({
            ...prev,
            [name]: value,
        }));
    };

    const handleUniformChange = (idUniform) => {
        setSelectedUniforms((prev) =>
            prev.includes(idUniform)
                ? prev.filter((u) => u !== idUniform)
                : [...prev, idUniform]
        );
    };

    // 🔹 Guardar cambios
    const handleSave = async () => {
        setError(null);
        setSuccessMsg("");
        try {
            const payload = {
                name_employee: form.name_employee,
                id_position_emp: Number(form.id_position_emp),
                id_area_emp: Number(form.id_area_emp),
                start_contract: form.start_contract,
                end_contract: form.end_contract,
                status_contract:
                    form.status_contract === "Active"
                        ? 1
                        : form.status_contract === "Inactive"
                            ? 2
                            : 3,
                new_daily_pay: Number(form.new_daily_pay) || 0,
                uniforms: selectedUniforms.map((id) => ({ id_uniform: id })),
            };

            console.log("📤 Payload enviado:", payload);

            const response = await fetch(
                `${import.meta.env.VITE_API_BASE_URL}/contracts/updatecontract/${id}`,
                {
                    method: "PUT",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify(payload),
                }
            );

            if (!response.ok) {
                const errData = await response.json();
                throw new Error(errData.message || "Error updating contract");
            }

            setSuccessMsg("Contract updated successfully!");
        } catch (err) {
            console.error("❌ Server error:", err);
            setError(`Server error: ${err.message}`);
        }
    };

    if (loading)
        return <div style={{ textAlign: "center" }}>Loading...</div>;

    return (
        <div className="contract-detail-container">
            <h2>Edit Contract (ID: {id})</h2>

            {error && <p className="error-text">{error}</p>}
            {successMsg && <p className="success-text">{successMsg}</p>}

            <div className="form-grid">
                {/* Name Empployee */}
                <div>
                    <label>Employee Name:</label>
                    <input
                        type="text"
                        name="name_employee"
                        value={form.name_employee}
                        readOnly //lo puedes quitar si quieres hacerlo editable
                    />

                </div>

                {/* Position */}
                <div>
                    <label>Position</label>
                    <select
                        name="id_position_emp"
                        value={form.id_position_emp}
                        onChange={handleChange}
                    >
                        <option value="">Select position</option>
                        {positions.map((p) => (
                            <option key={p.id_position} value={p.id_position}>
                                {p.name_position}
                            </option>
                        ))}
                    </select>

                </div>

                {/* Area */}
                <div>
                    <label>Area</label>
                    <select
                        name="id_area_emp"
                        value={form.id_area_emp}
                        onChange={handleChange}
                    >
                        <option value="">Select area</option>
                        {areas.map((a) => (
                            <option key={a.id} value={a.id}>
                                {a.name}
                            </option>
                        ))}
                    </select>
                </div>

                {/* Start & End Dates */}
                <div>
                    <label>Start Date</label>
                    <input
                        type="date"
                        name="start_contract"
                        value={form.start_contract}
                        onChange={handleChange}
                    />
                </div>

                <div>
                    <label>End Date</label>
                    <input
                        type="date"
                        name="end_contract"
                        value={form.end_contract}
                        onChange={handleChange}
                    />
                </div>

                {/* Status */}
                <div>
                    <label>Status</label>
                    <input type="text" value={form.status_contract} disabled />
                </div>

                {/* Daily Pay */}
                <div>
                    <label>Daily Pay</label>
                    <input
                        type="number"
                        name="new_daily_pay"
                        value={form.new_daily_pay}
                        onChange={handleChange}
                    />
                </div>

                {/* Uniforms */}
                <div className="uniforms-section">
                    <label>Uniforms</label>
                    <div className="uniform-list">
                        {uniforms.map((u) => (
                            <label key={`uniform-${u.id}`}>
                                <input
                                    type="checkbox"
                                    checked={selectedUniforms.includes(u.id)}
                                    onChange={() => handleUniformChange(u.id)}
                                />
                                {u.name}
                            </label>
                        ))}
                    </div>
                </div>
            </div>

            {/* Save Button */}
            <div className="save-button-container">
                <button onClick={handleSave}>Save Changes</button>
            </div>
        </div>
    );
}

