import React, { useEffect, useState, useContext } from 'react';
import '../../components/Filters/Filters.css';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import { langContext } from '../../context/LenguageContext';

export default function NewEmployee(){
  const { lang } = useContext(langContext);
  const { id: paramId } = useParams();
  
  const isEditMode = !!paramId;
  const nssParam = paramId;

  const [formState, setFormState] = useState({
    name_emp: "",
    rfc_emp: "",
    nss_emp: "",
    addres_emp: "",
    phone_emp: "",
    email_emp: "",
    birthday_emp: "",
    curp_emp: ""
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [fetchingEmployee, setFetchingEmployee] = useState(false);

  useEffect(() => {
    if (!isEditMode) {
      setFormState({
        name_emp: "",
        rfc_emp: "",
        nss_emp: "",
        addres_emp: "",
        phone_emp: "",
        email_emp: "",
        birthday_emp: "",
        curp_emp: ""
      });
      setError(null);
    }
  }, [isEditMode]);

  useEffect(() => {
    if (isEditMode && nssParam) {
      setFetchingEmployee(true);
      setError(null);
      
      axios.get(`${import.meta.env.VITE_API_BASE_URL}/employees?limit=1000&page=1`)
        .then((res) => {
          const employees = res.data?.data || [];
          const employee = employees.find(emp => String(emp.nss_employe) === String(nssParam));
          
          if (employee && employee.employee_rfc) {
            return axios.post(`${import.meta.env.VITE_API_BASE_URL}/employees/employee`, {
              rfcEmployee: employee.employee_rfc
            });
          } else {
            throw new Error("Employee not found or missing RFC");
          }
        })
        .then((res) => {
          const employeeData = res.data?.data;
          
          if (employeeData && Array.isArray(employeeData) && employeeData.length > 0) {
            const emp = employeeData[0];
            
            let formattedBirthday = '';
            if (emp.birthday) {
              const date = new Date(emp.birthday);
              if (!isNaN(date.getTime())) {
                formattedBirthday = date.toISOString().split('T')[0];
              }
            }

            const newFormState = {
              name_emp: String(emp.name_emp || ""),
              rfc_emp: String(emp.rfc_emp || ""),
              nss_emp: String(emp.nss_emp || ""),
              addres_emp: String(emp.addres_emp || ""),
              phone_emp: String(emp.phone_emp || ""),
              email_emp: String(emp.email_emp || ""),
              birthday_emp: String(formattedBirthday || ""),
              curp_emp: String(emp.curp || "")
            };
            setFormState(newFormState);
          } else if (employeeData === 0 || !employeeData) {
            setError(lang === "es" ? "Empleado no encontrado" : "Employee not found");
          }
        })
        .catch((err) => {
          console.error("Error fetching employee:", err);
          setError(lang === "es" ? "Error al cargar el empleado" : "Error loading employee");
        })
        .finally(() => {
          setFetchingEmployee(false);
        });
    }
  }, [isEditMode, nssParam, lang]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormState((prev) => ({ ...prev, [name]: value }));
  };

  const handleSave = () => {
    setLoading(true);
    setError(null);
    
    const payload = {
      ...formState
    };

    const endpoint = isEditMode 
      ? `${import.meta.env.VITE_API_BASE_URL}/employees/updateemployee`
      : `${import.meta.env.VITE_API_BASE_URL}/employees/newemployee`;

    axios.post(endpoint, payload)
      .then(() => {
        const successMsg = isEditMode
          ? (lang === "es" ? "Empleado actualizado correctamente" : "Employee updated successfully")
          : (lang === "es" ? "Empleado guardado con éxito" : "Employee saved successfully");
        alert(successMsg);
      })
      .catch((err) => {
        console.error(err);
        const errorMsg = isEditMode
          ? (lang === "es" ? "Error al actualizar el empleado" : "Error updating employee")
          : (lang === "es" ? "Error al guardar el empleado" : "Error saving employee");
        alert(errorMsg);
      })
      .finally(() => {
        setLoading(false);
      });
  };
  if (fetchingEmployee) {
    return (
      <div className="new-expense-container">
        <div>{lang === "es" ? "Cargando empleado..." : "Loading employee..."}</div>
      </div>
    );
  }

  return (
    <div className="new-expense-container">
      <h2>{isEditMode ? (lang === "es" ? "Editar empleado" : "Edit Employee") : (lang === "es" ? "Insertar empleado" : "Insert Employee")}</h2>
      {error && (
        <div style={{ color: 'red', marginBottom: '15px', padding: '10px', backgroundColor: '#ffebee', borderRadius: '4px' }}>
          {error}
        </div>
      )}
      <div className="form-card">
        <div className="form-grid">
          <div>
            <label>{lang === "es" ? "Nombre: " : "Name: "}</label>
            <input
              type="text"
              name="name_emp"
              value={formState.name_emp || ""}
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>

          <div>
            <label>{lang === "es" ? "RFC" : "RFC"}</label>
            <input 
              type="text" 
              name="rfc_emp" 
              value={formState.rfc_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>

          <div>
            <label>{lang === "es" ? "CURP" : "CURP"}</label>
            <input 
              type="text" 
              name="curp_emp" 
              value={formState.curp_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>

          <div>
            <label>{lang === "es" ? "NSS" : "NSS"}</label>
            <input 
              type="text" 
              name="nss_emp" 
              value={formState.nss_emp || ""} 
              onChange={handleChange}
              readOnly={isEditMode}
              className={isEditMode ? "readonly-input" : ""}
              style={isEditMode ? { backgroundColor: '#f5f5f5', cursor: 'not-allowed', color: '#000000' } : { color: '#000000' }}
            />
          </div>

          <div>
            <label>{lang === "es" ? "Dirección" : "Address"}</label>
            <input 
              type="text" 
              name="addres_emp" 
              value={formState.addres_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div> 
          <div>
            <label>{lang === "es" ? "Teléfono" : "Phone"}</label>
            <input 
              type="text" 
              name="phone_emp" 
              value={formState.phone_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>
          <div>
            <label>{lang === "es" ? "Correo electrónico" : "Email"}</label>
            <input 
              type="email" 
              name="email_emp" 
              value={formState.email_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>
          <div>
            <label>{lang === "es" ? "Fecha de nacimiento" : "Birthday"}</label>
            <input 
              type="date" 
              name="birthday_emp" 
              value={formState.birthday_emp || ""} 
              onChange={handleChange}
              style={{ color: '#000000' }}
            />
          </div>
        </div>
        <div className="save-button-wrapper">
          <button 
            className="save-button" 
            onClick={handleSave}
            disabled={loading}
          >
            {loading 
              ? (lang === "es" ? "Guardando..." : "Saving...")
              : (isEditMode 
                  ? (lang === "es" ? "Actualizar" : "Update")
                  : (lang === "es" ? "Guardar" : "Save")
                )
            }
          </button>
        </div>
      </div>
    </div>
  );
}