import React, { useState, useEffect, useCallback, useRef } from "react";
import { Clock } from "lucide-react";
import "./HorariosDisponibilidade.css";

const initialBlockTemplate = {
  id: null,
  inicio: "07:00",
  termino: "18:00",
  isNew: true,
};

const emptyAvailabilityTemplate = [
  { dia: "Domingo", weekday: 0, isChecked: false, blocos: [] },
  { dia: "Segunda-feira", weekday: 1, isChecked: false, blocos: [] },
  { dia: "Terça-feira", weekday: 2, isChecked: false, blocos: [] },
  { dia: "Quarta-feira", weekday: 3, isChecked: false, blocos: [] },
  { dia: "Quinta-feira", weekday: 4, isChecked: false, blocos: [] },
  { dia: "Sexta-feira", weekday: 5, isChecked: false, blocos: [] },
  { dia: "Sábado", weekday: 6, isChecked: false, blocos: [] },
];

const HorariosDisponibilidade = ({
  initialAvailability = emptyAvailabilityTemplate,
  onUpdate,
  onCancel,
}) => {
  const [availability, setAvailability] = useState(initialAvailability);
  const isFirstRun = useRef(true);

  useEffect(() => {
    if (initialAvailability && initialAvailability.length > 0) {
      setAvailability(initialAvailability);
    } else {
      setAvailability(emptyAvailabilityTemplate);
    }
  }, [initialAvailability]);

  useEffect(() => {
    if (isFirstRun.current) {
      isFirstRun.current = false;
      return;
    }
    if (onUpdate) onUpdate(availability);
  }, [availability, onUpdate]);

  const handleDayCheck = useCallback((dayIndex, currentIsChecked) => {
    const isChecked = !currentIsChecked;
    setAvailability((prev) => {
      const updated = prev.map((day, i) =>
        i === dayIndex
          ? {
              ...day,
              isChecked,
              blocos: isChecked
                ? day.blocos.length === 0
                  ? [
                      {
                        ...initialBlockTemplate,
                        id: Date.now() + Math.random(),
                        isNew: true,
                      },
                    ]
                  : day.blocos
                : [],
            }
          : day
      );
      console.log('handleDayCheck - updated availability:', updated);
      return updated;
    });
  }, []);

  const handleAddBlock = useCallback((dayIndex) => {
    const tempId = Date.now() + Math.random();
    const newBlock = { ...initialBlockTemplate, id: tempId, isNew: true };
    setAvailability((prev) =>
      prev.map((day, i) =>
        i === dayIndex
          ? {
              ...day,
              blocos: [...day.blocos, newBlock],
              isChecked: true,
            }
          : day
      )
    );
  }, []);

  const handleRemoveBlock = useCallback((dayIndex, blockId) => {
    setAvailability((prev) =>
      prev.map((day, i) => {
        if (i === dayIndex) {
          const newBlocos = day.blocos.filter((bloco) => bloco.id !== blockId);
          return {
            ...day,
            blocos: newBlocos,
            isChecked: newBlocos.length > 0,
          };
        }
        return day;
      })
    );
  }, []);

  const handleTimeChange = useCallback((dayIndex, blockId, field, value) => {
    setAvailability((prev) =>
      prev.map((day, i) =>
        i === dayIndex
          ? {
              ...day,
              blocos: day.blocos.map((bloco) =>
                bloco.id === blockId ? { ...bloco, [field]: value } : bloco
              ),
            }
          : day
      )
    );
  }, []);

  

  return (
    <div className="horarios-container">
      {availability.map((day, dayIndex) => (
        <div key={day.dia} className="day-card">
          <div
            className={`day-header ${day.isChecked ? "checked" : ""}`}
            onClick={() => handleDayCheck(dayIndex, day.isChecked)}
          >
            <label>
              <span>{day.dia}</span>
              <input type="checkbox" checked={day.isChecked} readOnly />
            </label>
          </div>

          {day.isChecked && (
            <div className="blocks-section">
              <div className="blocks-grid">
                {day.blocos.map((bloco) => (
                  <div
                    key={bloco.id}
                    className={`time-block ${bloco.isNew ? "new" : ""}`}
                  >
                    <div className="time-inputs">
                      <label>
                        Início:
                        <div className="input-wrapper">
                          <input
                            type="time"
                            value={bloco.inicio}
                            onChange={(e) =>
                              handleTimeChange(
                                dayIndex,
                                bloco.id,
                                "inicio",
                                e.target.value
                              )
                            }
                          />
                          <Clock className="clock-icon" size={14} />
                        </div>
                      </label>

                      <label>
                        Término:
                        <div className="input-wrapper">
                          <input
                            type="time"
                            value={bloco.termino}
                            onChange={(e) =>
                              handleTimeChange(
                                dayIndex,
                                bloco.id,
                                "termino",
                                e.target.value
                              )
                            }
                          />
                          <Clock className="clock-icon" size={14} />
                        </div>
                      </label>
                    </div>

                    <button
                      className="btn-remove"
                      onClick={() => handleRemoveBlock(dayIndex, bloco.id)}
                    >
                      Remover
                    </button>
                  </div>
                ))}
              </div>

              <button
                className="btn-add"
                onClick={() => handleAddBlock(dayIndex)}
              >
                + Adicionar novo bloco
              </button>
            </div>
          )}
        </div>
      ))}
    </div>
  );
};

export default HorariosDisponibilidade;
