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

export default function Plantillapayroll() {
  const { lang } = useContext(langContext);
  const { id } = useParams();
  
  const isNumericId = id && !isNaN(Number(id)) && Number(id) > 0;
  const contractId = isNumericId ? id : null;

  const [areas, setAreas] = useState([]);
  const [positions, setPositions] = useState([]);
  const [uniformsList, setUniformsList] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [formState, setFormState] = useState({
    rfc_emp: '',
    selectedEmployee: '',
    id_position_emp: '',
    id_area_emp: '',
    start_contract: '',
    end_contract: '',
    new_daily_pay: 600.0,
    uniforms: []
  });

  const formatDateForInput = (dateStr) => {
    if (!dateStr) return '';
    if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) return dateStr;
    return dateStr.slice(0, 10);
  };

  useEffect(() => {
    Promise.all([
      fetch(import.meta.env.VITE_API_BASE_URL + '/contracts/areas').then(res => res.json()),
      fetch(import.meta.env.VITE_API_BASE_URL + '/contracts/positions').then(res => res.json()),
      fetch(import.meta.env.VITE_API_BASE_URL + '/expenses/getinfo').then(res => res.json()),
      fetch(import.meta.env.VITE_API_BASE_URL + '/employees').then(res => res.json())
    ])
      .then(([areasData, positionsData, getInfoData, activeEmployeesData]) => {
        setAreas(areasData.data || []);
        setPositions(positionsData.data || []);
        setUniformsList(getInfoData.uniforms || []);

        const employeesData = activeEmployeesData.data || [];
        const uniqueEmployees = employeesData.filter((emp, index, self) =>
          index === self.findIndex(e => 
            e.name_employee?.toLowerCase().trim() === emp.name_employee?.toLowerCase().trim()
          )
        );
        setEmployees(uniqueEmployees);
      })
      .catch(() => console.warn("Error cargando datos iniciales"));
  }, []);

  useEffect(() => {
    if (!isNumericId) {
      setFormState({
        rfc_emp: '',
        selectedEmployee: '',
        id_position_emp: '',
        id_area_emp: '',
        start_contract: '',
        end_contract: '',
        new_daily_pay: 600.0,
        uniforms: []
      });
      setError(null);
      setLoading(false);
    }
  }, [isNumericId]);

  useEffect(() => {
    if (!contractId || !areas.length || !positions.length || !employees.length || !uniformsList.length) {
      return;
    }

    const fetchContractInfo = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/contracts/getinfocontract/${contractId}`);
        const data = await response.json();
        

        if (!data.data || data.data.length === 0) {
          setError(lang === 'es' ? 'Contrato no encontrado' : 'Contract not found');
          setLoading(false);
          return;
        }

        const contract = data.data[0];

        const employeeMatch = employees.find(
          (emp) => emp.name_employee?.toLowerCase().trim() === contract.name_employee?.toLowerCase().trim()
        );

        const employeeRfc = employeeMatch?.employee_rfc || employeeMatch?.rfc_emp || contract.rfc_emp || '';

        const positionMatch = positions.find(
          (p) => p.name_position?.toLowerCase().trim() === contract.position_employee?.toLowerCase().trim()
        );

        const areaMatch = areas.find(
          (a) => a.name_area?.toLowerCase().trim() === contract.area_employee?.toLowerCase().trim()
        );

        let uniformIds = [];
        if (contract.uniforms) {
          if (Array.isArray(contract.uniforms)) {
            uniformIds = contract.uniforms.map(u => {
              if (typeof u === 'object' && u !== null) {
                return String(u.id_uniform || u.id || u);
              }
              if (typeof u === 'string') {
                const uniformMatch = uniformsList.find(uni => uni.name === u || uni.name_uniform === u);
                return uniformMatch ? String(uniformMatch.id || uniformMatch.id_uniform) : '';
              }
              return String(u);
            }).filter(id => id);
          } else if (typeof contract.uniforms === 'object') {
            uniformIds = Object.values(contract.uniforms).map(u => {
              if (typeof u === 'object' && u !== null) {
                return String(u.id_uniform || u.id || u);
              }
              if (typeof u === 'string') {
                const uniformMatch = uniformsList.find(uni => uni.name === u || uni.name_uniform === u);
                return uniformMatch ? String(uniformMatch.id || uniformMatch.id_uniform) : '';
              }
              return String(u);
            }).filter(id => id);
          }
        }

        setFormState({
          rfc_emp: employeeRfc,
          selectedEmployee: contract.name_employee || '',
          id_position_emp: positionMatch?.id_position || '',
          id_area_emp: areaMatch?.id_area || '',
          start_contract: formatDateForInput(contract.contract_start),
          end_contract: formatDateForInput(contract.contract_end),
          new_daily_pay: contract.daily_pay || 600.0,
          uniforms: uniformIds
        });

        setLoading(false);
      } catch (err) {
        console.error('Error fetching contract info:', err);
        setError(lang === 'es' ? 'Error al cargar el contrato' : 'Error loading contract');
        setLoading(false);
      }
    };

    fetchContractInfo();
  }, [contractId, areas, positions, employees, uniformsList, lang]);

  const handleEmployeeChange = (e) => {
    const selectedName = e.target.value;
    const selectedEmp = employees.find(emp => emp.name_employee === selectedName);
    const employeeRfc = selectedEmp?.employee_rfc || selectedEmp?.rfc_emp || '';
    setFormState(prev => ({
      ...prev,
      selectedEmployee: selectedName,
      rfc_emp: employeeRfc
    }));
  };

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

  const handleUniformToggle = (id) => {
    setFormState(prev => {
      const exists = prev.uniforms.includes(String(id));
      return {
        ...prev,
        uniforms: exists
          ? prev.uniforms.filter(u => u !== String(id))
          : [...prev.uniforms, String(id)]
      };
    });
  };

  const removeUniform = (id) => {
    setFormState(prev => ({
      ...prev,
      uniforms: prev.uniforms.filter(u => String(u) !== String(id))
    }));
  };

  const handleSave = async () => {
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const [year, month, day] = dateStr.split('-');
      return `${year}-${month}-${day}`;
    };

    const payload = {
      rfc_emp: formState.rfc_emp,
      id_position_emp: parseInt(formState.id_position_emp) || null,
      id_area_emp: parseInt(formState.id_area_emp) || null,
      start_contract: formatDate(formState.start_contract),
      end_contract: formatDate(formState.end_contract),
      new_daily_pay: parseFloat(formState.new_daily_pay) || 0,
      uniforms: formState.uniforms.map(id => ({ id_uniform: parseInt(id) }))
    };

    if (contractId) {
      payload.name_employee = formState.selectedEmployee;
    }

    try {
      const url = contractId 
        ? `${import.meta.env.VITE_API_BASE_URL}/contracts/updatecontract/${contractId}`
        : `${import.meta.env.VITE_API_BASE_URL}/contracts/newcontract`;
      
      const method = contractId ? 'PUT' : 'POST';

      const res = await fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      if (res.ok) {
        const successMsg = contractId 
          ? (lang === 'es' ? 'Contrato actualizado correctamente' : 'Contract updated successfully')
          : (lang === 'es' ? 'Contrato guardado correctamente' : 'Contract saved successfully');
        alert(successMsg);
      } else {
        const errorMsg = contractId
          ? (lang === 'es' ? 'Error al actualizar el contrato' : 'Error updating contract')
          : (lang === 'es' ? 'Error al guardar el contrato' : 'Error saving contract');
        alert(errorMsg);
      }
    } catch {
      const errorMsg = contractId
        ? (lang === 'es' ? 'Error de red al actualizar el contrato' : 'Network error updating contract')
        : (lang === 'es' ? 'Error de red al guardar el contrato' : 'Network error saving contract');
      alert(errorMsg);
    }
  };

  if (!areas.length || !positions.length) {
    return <div>{lang === "es" ? "Cargando datos..." : "Loading data..."}</div>;
  }

  if (loading) {
    return <div>{lang === "es" ? "Cargando contrato..." : "Loading contract..."}</div>;
  }

  return (
    <div className="new-expense-container">
      <h2>{contractId ? (lang === "es" ? "Editar Contrato" : "Edit Contract") : (lang === "es" ? "Nuevo Contrato" : "New Contract")}</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" ? "Empleado" : "Employee"}</label>
            <select
              name="selectedEmployee"
              value={formState.selectedEmployee || ''}
              onChange={handleEmployeeChange}
            >
              <option value="">{lang === "es" ? "Selecciona un empleado" : "Select an employee"}</option>
              {employees
                .sort((a, b) => a.name_employee.localeCompare(b.name_employee))
                .map(emp => (
                  <option key={emp.employee_rfc || emp.rfc_emp || emp.name_employee} value={emp.name_employee}>
                    {emp.name_employee}
                  </option>
                ))}
            </select>
          </div>

          <div>
            <label>RFC</label>
            <input
              type="text"
              name="rfc_emp"
              value={formState.rfc_emp || ''}
              readOnly
              className="readonly-input"
              style={{ color: '#000000' }}
            />
          </div>

          <div>
            <label>{lang === "es" ? "Posición" : "Position"}</label>
            <select
              name="id_position_emp"
              value={formState.id_position_emp || ''}
              onChange={handleChange}
            >
              <option value="">{lang === "es" ? "Selecciona una posición" : "Select a position"}</option>
              {positions
                .sort((a, b) => {
                  const nameA = lang === "en" ? a.name_position : a.spanish_name;
                  const nameB = lang === "en" ? b.name_position : b.spanish_name;
                  return nameA.localeCompare(nameB);
                })
                .map(p => (
                  <option key={p.id_position} value={p.id_position}>
                    {lang === "en" ? p.name_position : p.spanish_name}
                  </option>
                ))}
            </select>
          </div>

          <div>
            <label>{lang === "es" ? "Área" : "Area"}</label>
            <select
              name="id_area_emp"
              value={formState.id_area_emp || ''}
              onChange={handleChange}
            >
              <option value="">{lang === "es" ? "Selecciona un área" : "Select an area"}</option>
              {areas
                .sort((a, b) => a.name_area.localeCompare(b.name_area))
                .map(a => (
                  <option key={a.id_area} value={a.id_area}>
                    {a.name_area}
                  </option>
                ))}
            </select>
          </div>

          <div>
            <label>{lang === "es" ? "Inicio del contrato" : "Contract Start"}</label>
            <input
              type="date"
              name="start_contract"
              value={formState.start_contract || ''}
              onChange={handleChange}
            />
          </div>

          <div>
            <label>{lang === "es" ? "Fin del contrato" : "Contract End"}</label>
            <input
              type="date"
              name="end_contract"
              value={formState.end_contract || ''}
              onChange={handleChange}
            />
          </div>

          <div>
            <label>{lang === "es" ? "Pago diario" : "Daily pay"}</label>
            <input
              type="number"
              name="new_daily_pay"
              value={formState.new_daily_pay || ''}
              onChange={handleChange}
            />
          </div>

          <div className="uniform-section">
            <label>{lang === "es" ? "Uniformes" : "Uniforms"}</label>
            <div className="uniform-checkbox-list">
              {uniformsList.map(u => (
                <label key={u.id} className="checkbox-item">
                  <div className="checkbox-item-content">
                    <input
                      type="checkbox"
                      checked={formState.uniforms.includes(String(u.id))}
                      onChange={() => handleUniformToggle(u.id)}
                    />
                    {u.name}
                  </div>
                </label>
              ))}
            </div>

            <div className="uniform-chips">
              {formState.uniforms.map(id => {
                const uniform = uniformsList.find(u => String(u.id) === String(id));
                return (
                  <span key={id} className="chip">
                    {uniform ? uniform.name : `Uniforme ${id}`}
                    <button
                      className="remove-chip"
                      onClick={() => removeUniform(id)}
                    >
                      ×
                    </button>
                  </span>
                );
              })}
            </div>
          </div>
        </div>

        <div className="save-button-wrapper">
          <button className="save-button" onClick={handleSave}>
            {contractId ? (lang === 'es' ? 'Actualizar' : 'Update') : (lang === 'es' ? 'Guardar' : 'Save')}
          </button>
        </div>
      </div>
    </div>
  );
}
