import React, { useEffect, useState  } from 'react';
import axios from 'axios';
import '../../components/Filters/Filters.css';
import Table from '../../components/Table/HotelTable';
import { Link, useParams } from 'react-router-dom';
import FormInput from '../../components/FormInput';

export default function Plantillapayroll(){
    const { id: paramId } = useParams();
    function generateRandomId() {
      return Math.floor(1000 + Math.random() * 9000); // 4 dígitos
    }
    let id = paramId;
    const [contracts, setContracts] = useState([]);
    const [contractId, setContractId] = useState(null);
    const [formData, setFormData] = useState(null);

    // Consultar contratos al montar el componente
    useEffect(() => {
      axios.get(import.meta.env.VITE_API_BASE_URL + '/reportcontracts')
        .then(res => {
          if (Array.isArray(res.data?.data)) {
            setContracts(res.data.data);
          }
        })
        .catch(() => setContracts([]));
    }, []);

    // Determinar el contrato a mostrar/editar cuando cambian los contratos o el id
    useEffect(() => {
      let contractIdValue;
      if (!id || isNaN(Number(id))) {
        contractIdValue = contracts.length > 0 ? contracts.length + 1 : 1;
      } else {
        contractIdValue = Number(id);
      }
      setContractId(contractIdValue);
      // Buscar el contrato por índice (ya que no hay id_contract en la API)
      const contrato = contracts.find(c => c.id_contract === contractIdValue) || {
        id_contract: contractIdValue,
        name_employee: "",
        position_employee: "",
        area_employee: "",
        contract_start: "",
        contract_end: "",
        status_contract: ""
      };
      // Si el contrato tiene área, asegúrate de que el campo esté presente y no sea null/undefined
      setFormData({
        ...contrato
      });
    }, [contracts, id]);
      // Estados para áreas y posiciones consultadas
      const [areas, setAreas] = useState([]);
      const [positions, setPositions] = useState([]);

      // Consultar áreas y posiciones al montar el componente
      useEffect(() => {
        // Consulta de áreas
        axios.get(import.meta.env.VITE_API_BASE_URL + '/contracts')
            .then(res => {
              if (Array.isArray(res.data?.data) && res.data.data.length > 0) {
                setAreas(res.data.data.map(a => a.name_area));
              } else {
                // Si la consulta de áreas está vacía, usar los valores únicos de area_employee de los contratos
                const uniqueAreas = Array.from(new Set(contracts.map(c => c.area_employee).filter(Boolean)));
                setAreas(uniqueAreas);
              }
            })
          .catch(() => {
            // Si falla la consulta, usar los valores únicos de area_employee de los contratos
            const uniqueAreas = Array.from(new Set(contracts.map(c => c.area_employee).filter(Boolean)));
            setAreas(uniqueAreas);
          });
        // Consulta de posiciones
        axios.get(import.meta.env.VITE_API_BASE_URL + '/contracts/positions')
            .then(res => {
              if (Array.isArray(res.data?.data)) {
                setPositions(res.data.data.map(p => p.name_position));
              }
            })
          .catch(() => setPositions([]));
      }, [contracts]);
    
      const handleChange = (e) => {
        const { name, value } = e.target;
  setFormData((prev) => ({ ...prev, [name]: value }));
      };
    
      // ...existing code...
    
     return (
  <div className="new-expense-container">
    <h2>Insert/Update Contract</h2>
    <div className="form-card">
      <div className="form-id">ID #{contractId}</div>
      <div className="form-grid">
        <div>
          <label>Name: </label>
          <input
            type="text"
            name="name_employee"
            value={formData?.name_employee || ""}
            onChange={handleChange}
          />
        </div>
        <div>
          <label>Position</label>
          <select name="position_employee" value={formData?.position_employee || ""} onChange={handleChange}>
            <option value="">Select position</option>
            {positions.map((position) => (
              <option key={position} value={position}>{position}</option>
            ))}
          </select>
        </div>
        <div>
          <label>Area</label>
          <select name="area_employee" value={formData?.area_employee || ""} onChange={handleChange}>
            <option value="">Select area</option>
            {!areas.includes(formData?.area_employee) && formData?.area_employee && (
              <option value={formData.area_employee}>{formData.area_employee}</option>
            )}
            {areas.map((area) => (
              <option key={area} value={area}>{area}</option>
            ))}
          </select>
        </div>
        <div>
          <label>Start of contract</label>
          <input
            type="date"
            name="contract_start"
            value={formData?.contract_start?.slice(0,10) || ""}
            onChange={handleChange}
          />
        </div>
        <div>
          <label>End of contract</label>
          <input
            type="date"
            name="contract_end"
            value={formData?.contract_end?.slice(0,10) || ""}
            onChange={handleChange}
          />
        </div>
        <div>
          <label>Status</label>
          <select name="status_contract" value={formData?.status_contract || ""} onChange={handleChange}>
            <option value="">Select status</option>
            <option value="Active">Active</option>
            <option value="Inactive">Inactive</option>
            <option value="Pending">Pending</option>
            <option value="Terminated">Terminated</option>
          </select>
        </div>
      </div>
    </div>
  </div>
);
}