const ProfileScreen = ({ onLogout, onViewPartner }) => {
  const {
    snapshot,
    viewer,
    partnerProfile,
    updateWeeklyGoal,
    closeWeeklyGoal,
    openGoogleConnect,
    disconnectGoogle
  } = useAinaApp();
  const [goalTitle, setGoalTitle] = React.useState("");
  const [goalWhy, setGoalWhy] = React.useState("");
  const [closeStatus, setCloseStatus] = React.useState("done");
  const [closeReflection, setCloseReflection] = React.useState("");

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

    setGoalTitle(weekly.goal?.title || "");
    setGoalWhy(weekly.goal?.why || "");
    setCloseStatus(weekly.goal?.status === "missed" ? "missed" : "done");
    setCloseReflection(weekly.goal?.reflection || "");
  }, [snapshot]);

  if (!snapshot?.selectedProfile || !viewer) {
    return <LoadingState title="Yo" body="Cargando tu perfil real..." />;
  }

  const profile = snapshot.selectedProfile;
  const weekly = profile.weekly || snapshot.weekly?.selectedProfile;
  const who = getWhoForName(profile.name);
  const calendarConnected = profile.calendar?.status === "connected";

  return (
    <div
      className="noscroll"
      style={{
        height: "100%",
        overflowY: "auto",
        padding: "54px 16px 110px"
      }}
    >
      <ScreenTitle sub={`Perfil de ${profile.name}`}>Yo</ScreenTitle>

      <Glass padding={18} radius={26} style={{ marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar who={who} size={64} />
          <div style={{ flex: 1 }}>
            <div className="serif" style={{ fontSize: 30, lineHeight: 1 }}>
              {profile.name}
            </div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginTop: 4 }}>
              {viewer.profileId}
            </div>
          </div>
          <div
            style={{
              width: 38,
              height: 38,
              borderRadius: 19,
              background: "rgba(255,255,255,0.08)",
              border: "0.5px solid rgba(255,255,255,0.14)",
              color: "#fff",
              display: "flex",
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <I.Edit size={16} />
          </div>
        </div>

        <div
          style={{
            display: "flex",
            justifyContent: "space-around",
            marginTop: 16,
            paddingTop: 14,
            borderTop: "0.5px solid rgba(255,255,255,0.1)"
          }}
        >
          {[
            { label: "Score hoy", value: profile.today.score },
            { label: "Racha", value: profile.stats.streakDays },
            { label: "7d", value: `${profile.stats.consistency7d}%` }
          ].map((stat) => (
            <div key={stat.label} style={{ textAlign: "center" }}>
              <div className="serif" style={{ fontSize: 26, lineHeight: 1 }}>
                {stat.value}
              </div>
              <div
                style={{
                  fontSize: 10,
                  letterSpacing: "0.12em",
                  textTransform: "uppercase",
                  color: "rgba(255,255,255,0.5)",
                  marginTop: 4
                }}
              >
                {stat.label}
              </div>
            </div>
          ))}
        </div>
      </Glass>

      <Glass padding={16} style={{ marginBottom: 12 }}>
        <SectionLabel
          icon={<I.Target size={12} />}
          action={
            <span style={{ fontSize: 11, color: "oklch(0.78 0.14 150)", fontWeight: 590 }}>
              {weekly?.stats?.activeDays || 0} / {weekly?.stats?.elapsedDays || 0} dias activos
            </span>
          }
        >
          Objetivo semanal
        </SectionLabel>
        <input
          value={goalTitle}
          onChange={(event) => setGoalTitle(event.target.value)}
          placeholder="Que quieres cerrar esta semana"
          style={{
            width: "100%",
            marginBottom: 10,
            background: "transparent",
            border: "none",
            outline: "none",
            color: "#fff",
            fontFamily: '"Instrument Serif", serif',
            fontSize: 22,
            lineHeight: 1.2
          }}
        />
        <textarea
          value={goalWhy}
          onChange={(event) => setGoalWhy(event.target.value)}
          placeholder="Por que importa"
          style={{
            width: "100%",
            minHeight: 72,
            padding: 12,
            borderRadius: 12,
            background: "rgba(0,0,0,0.22)",
            border: "0.5px solid rgba(255,255,255,0.1)",
            color: "#fff",
            fontFamily: "inherit",
            fontSize: 13,
            lineHeight: 1.5,
            outline: "none",
            resize: "none"
          }}
        />

        <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
          <PillBtn
            primary
            onClick={() =>
              updateWeeklyGoal({
                title: goalTitle,
                why: goalWhy
              }).catch(() => null)
            }
            style={{ flex: 1 }}
          >
            Guardar objetivo
          </PillBtn>
        </div>

        <div style={{ display: "flex", gap: 4, marginTop: 14 }}>
          {["done", "missed"].map((status) => (
            <button
              key={status}
              onClick={() => setCloseStatus(status)}
              style={{
                flex: 1,
                height: 36,
                borderRadius: 12,
                border: `0.5px solid ${
                  closeStatus === status ? "rgba(255,255,255,0.34)" : "rgba(255,255,255,0.14)"
                }`,
                background:
                  closeStatus === status ? "rgba(255,255,255,0.14)" : "rgba(255,255,255,0.04)",
                color: "#fff",
                cursor: "pointer",
                fontFamily: "inherit",
                fontSize: 12,
                fontWeight: 600
              }}
            >
              {status === "done" ? "Cumplido" : "Fallado"}
            </button>
          ))}
        </div>

        <textarea
          value={closeReflection}
          onChange={(event) => setCloseReflection(event.target.value)}
          placeholder="Que ha funcionado o que ha fallado"
          style={{
            width: "100%",
            minHeight: 72,
            padding: 12,
            borderRadius: 12,
            background: "rgba(0,0,0,0.22)",
            border: "0.5px solid rgba(255,255,255,0.1)",
            color: "#fff",
            fontFamily: "inherit",
            fontSize: 13,
            lineHeight: 1.5,
            outline: "none",
            resize: "none",
            marginTop: 10
          }}
        />

        <div style={{ marginTop: 10 }}>
          <PillBtn
            ghost
            onClick={() =>
              closeWeeklyGoal({
                status: closeStatus,
                reflection: closeReflection
              }).catch(() => null)
            }
            style={{ width: "100%" }}
          >
            Cerrar semana
          </PillBtn>
        </div>
      </Glass>

      <Glass soft padding={4} style={{ marginBottom: 12 }}>
        {[
          {
            icon: <I.Cal size={16} />,
            label: "Google Calendar",
            right: calendarConnected ? "Conectado" : "Sin conectar",
            onClick: () =>
              (calendarConnected ? disconnectGoogle() : openGoogleConnect()).catch(() => null)
          },
          {
            icon: <I.Bell size={16} />,
            label: "Notificaciones push",
            right: snapshot.notifications?.settings?.pushEnabled ? "Activas" : "Pendientes"
          },
          {
            icon: <I.Wifi size={16} />,
            label: "Sincronizacion",
            right: "Auto"
          },
          {
            icon: <I.User size={16} />,
            label: partnerProfile ? `Ver perfil de ${partnerProfile.name}` : "Ver pareja",
            onClick: onViewPartner
          }
        ].map((row, index, rows) => (
          <button
            key={row.label}
            onClick={row.onClick}
            style={{
              width: "100%",
              display: "flex",
              alignItems: "center",
              gap: 12,
              padding: "14px 12px",
              borderBottom:
                index < rows.length - 1 ? "0.5px solid rgba(255,255,255,0.08)" : "none",
              cursor: row.onClick ? "pointer" : "default",
              background: "transparent",
              borderLeft: 0,
              borderRight: 0,
              borderTop: 0,
              color: "#fff",
              textAlign: "left"
            }}
          >
            <div
              style={{
                width: 32,
                height: 32,
                borderRadius: 10,
                background: "rgba(255,255,255,0.08)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "#fff"
              }}
            >
              {row.icon}
            </div>
            <div style={{ flex: 1, fontSize: 14 }}>{row.label}</div>
            {row.right && (
              <span
                style={{
                  fontSize: 12,
                  color:
                    row.right === "Conectado" || row.right === "Activas"
                      ? "oklch(0.78 0.14 150)"
                      : "rgba(255,255,255,0.55)",
                  fontWeight: 500
                }}
              >
                {row.right}
              </span>
            )}
            <I.Chev size={14} color="rgba(255,255,255,0.4)" />
          </button>
        ))}
      </Glass>

      <Glass soft padding={14} style={{ marginBottom: 12 }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <div
            style={{
              width: 36,
              height: 36,
              borderRadius: 10,
              background: "rgba(255,255,255,0.08)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <I.Sparkle size={18} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 590 }}>Instalar como app</div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", marginTop: 2 }}>
              Compartir → Añadir a pantalla de inicio
            </div>
          </div>
        </div>
      </Glass>

      <button
        onClick={onLogout}
        style={{
          width: "100%",
          padding: 14,
          borderRadius: 16,
          background: "transparent",
          border: "0.5px solid rgba(255,255,255,0.14)",
          color: "oklch(0.74 0.13 18)",
          fontWeight: 590,
          fontSize: 14,
          cursor: "pointer",
          fontFamily: "inherit"
        }}
      >
        Cerrar sesion
      </button>
    </div>
  );
};

window.ProfileScreen = ProfileScreen;
