const CheckinScreen = ({ onClose }) => {
  const { snapshot, saveDay } = useAinaApp();
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    focus: "",
    gratitude: "",
    note: "",
    mood: 4
  });

  React.useEffect(() => {
    const today = snapshot?.selectedProfile?.today;
    if (!today) {
      return;
    }

    setData({
      focus: today.focus || "",
      gratitude: today.gratitude || "",
      note: today.journal || "",
      mood: Number.isInteger(today.mood) ? today.mood : 4
    });
  }, [snapshot]);

  const steps = ["Foco", "Gratitud", "Diario", "Estado"];

  const setField = (key, value) =>
    setData((current) => ({
      ...current,
      [key]: value
    }));

  const moods = [
    { value: 1, label: "mal", emoji: "😔" },
    { value: 2, label: "flojo", emoji: "😕" },
    { value: 3, label: "normal", emoji: "😐" },
    { value: 4, label: "bien", emoji: "🙂" },
    { value: 5, label: "genial", emoji: "😊" }
  ];

  const submit = async () => {
    if (step < 3) {
      setStep(step + 1);
      return;
    }

    await saveDay({
      focus: data.focus,
      gratitude: data.gratitude,
      journal: data.note,
      mood: data.mood
    }).catch(() => null);
    onClose();
  };

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 60,
        background: "rgba(10, 6, 18, 0.6)",
        backdropFilter: "blur(28px)",
        WebkitBackdropFilter: "blur(28px)",
        padding: "54px 16px 34px",
        display: "flex",
        flexDirection: "column"
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          marginBottom: 24
        }}
      >
        <button
          onClick={onClose}
          style={{
            width: 36,
            height: 36,
            borderRadius: 18,
            background: "rgba(255,255,255,0.08)",
            border: "0.5px solid rgba(255,255,255,0.14)",
            color: "#fff",
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center"
          }}
        >
          <I.Close size={16} />
        </button>
        <div style={{ display: "flex", gap: 4 }}>
          {steps.map((_, index) => (
            <div
              key={index}
              style={{
                width: index === step ? 22 : 8,
                height: 4,
                borderRadius: 2,
                background: index <= step ? "#fff" : "rgba(255,255,255,0.18)",
                transition: "width 0.25s"
              }}
            />
          ))}
        </div>
        <div style={{ width: 36 }} />
      </div>

      <div
        style={{
          fontSize: 11,
          letterSpacing: "0.18em",
          textTransform: "uppercase",
          color: "rgba(255,255,255,0.5)",
          marginBottom: 6,
          textAlign: "center"
        }}
      >
        Check-in · {steps[step]}
      </div>
      <div
        className="serif"
        style={{
          fontSize: 32,
          lineHeight: 1.1,
          textAlign: "center",
          marginBottom: 28,
          letterSpacing: "-0.015em"
        }}
      >
        {step === 0 && "Que te llevas hoy"}
        {step === 1 && "Algo por lo que estas agradecida hoy"}
        {step === 2 && "Una nota para ti"}
        {step === 3 && "Como te sientes ahora"}
      </div>

      <div style={{ flex: 1 }}>
        {step === 0 && (
          <textarea
            autoFocus
            placeholder="Tu foco del dia"
            value={data.focus}
            onChange={(event) => setField("focus", event.target.value)}
            style={inputStyle}
          />
        )}
        {step === 1 && (
          <textarea
            autoFocus
            placeholder="Cualquier cosa, pequena o grande"
            value={data.gratitude}
            onChange={(event) => setField("gratitude", event.target.value)}
            style={inputStyle}
          />
        )}
        {step === 2 && (
          <textarea
            autoFocus
            placeholder="Lo que sea. Esto solo lo ves tu."
            value={data.note}
            onChange={(event) => setField("note", event.target.value)}
            style={{ ...inputStyle, minHeight: 200 }}
          />
        )}
        {step === 3 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {moods.map((mood) => {
              const active = data.mood === mood.value;
              return (
                <button
                  key={mood.value}
                  onClick={() => setField("mood", mood.value)}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 14,
                    padding: "14px 16px",
                    borderRadius: 16,
                    background: active ? "rgba(255,255,255,0.16)" : "rgba(255,255,255,0.04)",
                    border: `0.5px solid ${
                      active ? "rgba(255,255,255,0.3)" : "rgba(255,255,255,0.1)"
                    }`,
                    color: "#fff",
                    cursor: "pointer",
                    fontFamily: "inherit"
                  }}
                >
                  <span style={{ fontSize: 28 }}>{mood.emoji}</span>
                  <span style={{ fontSize: 16, fontWeight: 500 }}>{mood.label}</span>
                </button>
              );
            })}
          </div>
        )}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 16 }}>
        {step > 0 && (
          <PillBtn ghost onClick={() => setStep(step - 1)} style={{ flex: 1 }}>
            Atras
          </PillBtn>
        )}
        <PillBtn primary size="lg" onClick={submit} style={{ flex: 2 }}>
          {step < 3 ? "Siguiente" : "Guardar check-in"}
        </PillBtn>
      </div>
    </div>
  );
};

const inputStyle = {
  width: "100%",
  minHeight: 120,
  padding: 18,
  resize: "none",
  background: "rgba(0,0,0,0.22)",
  border: "0.5px solid rgba(255,255,255,0.1)",
  borderRadius: 18,
  color: "#fff",
  fontFamily: "inherit",
  fontSize: 17,
  lineHeight: 1.5,
  outline: "none"
};

window.CheckinScreen = CheckinScreen;
