import React from "react";
import { ArrowLeft } from "lucide-react";

interface NotesStepProps {
  notesForm: {
    shippingDate: Date | null;
    scheduleDelivery: boolean;
    shippingPriority: "B" | "M" | "A";
    notesText1: string;
    notesText2: string;
    notesDeliveryText1: string;
    notesDeliveryText2: string;
    notesDeliveryText3: string;
  };
  onFormChange: (field: string, value: any) => void;
  onPrevious: () => void;
}

const NotesStep: React.FC<NotesStepProps> = ({
  notesForm,
  onFormChange,
  onPrevious,
}) => {
  // Função para formatar a data para o input type="date" (YYYY-MM-DD)
  const formatDateForInput = (date: Date | null): string => {
    if (!date) return "";

    try {
      // Verificar se é uma data válida
      if (isNaN(date.getTime())) {
        console.warn("📅 [NOTES_STEP] Data inválida:", date);
        return "";
      }

      // Formatar para YYYY-MM-DD
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    } catch (error) {
      console.error("📅 [NOTES_STEP] Erro ao formatar data:", error, date);
      return "";
    }
  };

  // Log para debug
  React.useEffect(() => {
    console.log(
      "📅 [NOTES_STEP] shippingDate recebido:",
      notesForm.shippingDate
    );
    console.log("📅 [NOTES_STEP] Tipo:", typeof notesForm.shippingDate);
    if (notesForm.shippingDate) {
      console.log(
        "📅 [NOTES_STEP] Data formatada:",
        formatDateForInput(notesForm.shippingDate)
      );
    }
  }, [notesForm.shippingDate]);

  return (
    <div className="animate-fade-in">
      <h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 mb-6">
        Observações
      </h3>

      <form className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
              Previsão de entrega
            </label>
            <input
              type="date"
              min={(() => {
                // Calcular data mínima (D+3)
                const today = new Date();
                today.setHours(0, 0, 0, 0);
                const minDate = new Date(today);
                minDate.setDate(today.getDate() + 3);
                // Formatar para YYYY-MM-DD
                const year = minDate.getFullYear();
                const month = String(minDate.getMonth() + 1).padStart(2, "0");
                const day = String(minDate.getDate()).padStart(2, "0");
                return `${year}-${month}-${day}`;
              })()}
              value={formatDateForInput(notesForm.shippingDate)}
              onChange={(e) => {
                const dateValue = e.target.value;
                console.log(
                  "📅 [NOTES_STEP] Valor do input alterado:",
                  dateValue
                );

                if (dateValue) {
                  // Criar data a partir do valor do input (YYYY-MM-DD)
                  // Usar data local para corresponder exatamente ao que o usuário selecionou
                  const [year, month, day] = dateValue.split("-").map(Number);
                  const date = new Date(year, month - 1, day);
                  // Zerar horas para garantir que seja apenas a data, sem hora
                  date.setHours(0, 0, 0, 0);

                  console.log(
                    "📅 [NOTES_STEP] Nova data criada (local):",
                    date
                  );
                  console.log(
                    "📅 [NOTES_STEP] Data formatada de volta:",
                    formatDateForInput(date)
                  );
                  onFormChange("shippingDate", date);
                } else {
                  console.log("📅 [NOTES_STEP] Data removida (null)");
                  onFormChange("shippingDate", null);
                }
              }}
              className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20"
            />
          </div>
          <div>
            <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
              Prioridade de Entrega
            </label>
            <div className="flex gap-4 mt-2">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="radio"
                  name="shippingPriority"
                  value="B"
                  checked={notesForm.shippingPriority === "B"}
                  onChange={(e) =>
                    onFormChange(
                      "shippingPriority",
                      e.target.value as "B" | "M" | "A"
                    )
                  }
                  className="w-4 h-4 text-[#002147] focus:ring-2 focus:ring-[#002147]"
                />
                <span className="text-sm font-medium text-slate-700">
                  Entrega
                </span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="radio"
                  name="shippingPriority"
                  value="M"
                  checked={notesForm.shippingPriority === "M"}
                  onChange={(e) =>
                    onFormChange(
                      "shippingPriority",
                      e.target.value as "B" | "M" | "A"
                    )
                  }
                  className="w-4 h-4 text-[#002147] focus:ring-2 focus:ring-[#002147]"
                />
                <span className="text-sm font-medium text-slate-700">
                  Retira
                </span>
              </label>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="radio"
                  name="shippingPriority"
                  value="A"
                  checked={notesForm.shippingPriority === "A"}
                  onChange={(e) =>
                    onFormChange(
                      "shippingPriority",
                      e.target.value as "B" | "M" | "A"
                    )
                  }
                  className="w-4 h-4 text-[#002147] focus:ring-2 focus:ring-[#002147]"
                />
                <span className="text-sm font-medium text-slate-700">
                  Delivery
                </span>
              </label>
            </div>
          </div>
        </div>

        <div>
          <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
            Observações do Pedido
          </label>
          <input
            type="text"
            maxLength={50}
            value={notesForm.notesText1}
            onChange={(e) => onFormChange("notesText1", e.target.value)}
            className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20 mb-2"
            placeholder="Observação 1"
          />
          <input
            type="text"
            maxLength={50}
            value={notesForm.notesText2}
            onChange={(e) => onFormChange("notesText2", e.target.value)}
            className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20"
            placeholder="Observação 2"
          />
        </div>

        <div>
          <label className="block text-[10px] font-black uppercase text-slate-400 mb-2">
            Observações de Entrega
          </label>
          <input
            type="text"
            maxLength={75}
            value={notesForm.notesDeliveryText1}
            onChange={(e) => onFormChange("notesDeliveryText1", e.target.value)}
            className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20 mb-2"
            placeholder="Observação de entrega 1"
          />
          <input
            type="text"
            maxLength={75}
            value={notesForm.notesDeliveryText2}
            onChange={(e) => onFormChange("notesDeliveryText2", e.target.value)}
            className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20 mb-2"
            placeholder="Observação de entrega 2"
          />
          <input
            type="text"
            maxLength={75}
            value={notesForm.notesDeliveryText3}
            onChange={(e) => onFormChange("notesDeliveryText3", e.target.value)}
            className="w-full px-4 py-3 bg-slate-50 rounded-xl font-bold text-[#002147] border border-slate-200 focus:outline-none focus:ring-2 focus:ring-orange-500/20"
            placeholder="Observação de entrega 3"
          />
        </div>

        <div className="flex justify-end gap-2 mt-6">
          <button
            type="button"
            onClick={onPrevious}
            className="flex items-center gap-2 bg-slate-100 px-6 py-2 rounded-lg text-[10px] font-black uppercase tracking-widest text-[#002147] hover:bg-slate-200 transition-colors"
          >
            <ArrowLeft className="w-4 h-4" />
            Retornar
          </button>
        </div>
      </form>
    </div>
  );
};

export default NotesStep;
